.jpg)
Here's an example of a nested if statement in Python:
# program to check if a number is positive, negative, or zero num = float(input("Enter a number: ")) if num >= 0: if num == 0: print("The number is zero.") else: print("The number is positive.") else: print("The number is negative.")
In this example, we first ask the user to enter a number. We then use a nested if statement to determine whether the number is positive, negative, or zero.
The first if statement checks whether the number is greater than or equal to zero. If the number is greater than or equal to zero, we move on to the nested if statement.
The nested if statement checks whether the number is equal to zero. If the number is equal to zero, we print "The number is zero." Otherwise, we print "The number is positive."
If the number is less than zero, we skip the nested if statement and move on to the else statement, which prints "The number is negative."
Nested if statements can be useful in many different programming scenarios. They allow us to test for multiple conditions and make decisions based on the outcome of each test.
0 Comments