Python nested-if statement
Nested if statements in any programming language means an if statement inside another if statement. Python also allows us to nest if statements within if statements. i.e, we can write an if statement inside another if statement.Syntax of nested-if statement:
if (condition 1):
# Code to be executed when condition 1 is true
if (condition 2):
# Code to be executed when condition 2 is true
# end of inner if Block
# end of outer if Block
Example of Nested-if Statement: Python program to check Positive, Negative or Zero number.
# Checking for Positive, Negative, or Zero Number
number = int(input("Enter one number:"))
if number >= 0:
if number == 0:
print("The number is zero")
else:
print("The number is positive")
else:
print("The number is negative")
Output of program
Enter a number:5The number is positive
if-elif-else ladder
The if statements are executed from the top to the bottom sequentially. When one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the last else statement written will be executed.
Syntax of if-elif-else
if (condition 1):statements for condition 1elif (condition 2):statements for condition 2..else:statements for else
Example of Python if-elif-else ladder
number = int(input("Enter number in range of 1 to 5:"))
if (number == 1):
print ("It’s One")
elif (number == 2):
print ("It’s Two")
elif (number == 3):
print ("It’s Three")
elif (number == 4):
print ("It’s Four")
elif (number == 5):
print ("It’s Five")
else:
print ("It’s not in range of 1 to 5")
Output of program
Enter number in range of 1 to 5:3It’s Three