A statement that contains other statements is called a compound statement. To perform more complex checks, if a statement can be nested, it can be placed one inside the other. In such a case, the inner if the statement is the statement part of the outer one. Nested if statements are used to check if more than one condition is satisfied.
Actually, when a series of decisions are involved, we may have to use more than one if…..else statement in nested form as follows:
if(test condition 1): if(test condition 2): statement-1 else: statement-2 else: statement-3 statement-x
Python Nested If Condition Examples
Here if condition 1 is false, then statement-3 is executed; otherwise, it continues to perform the second test. If condition 2 is true, the statement-1 is evaluated; otherwise, statement-2 is evaluated, and the control is transferred to the statement-x.
Example 1
number=int(input("Enter the value of number=")) if(number!=0): if(number>0): print("The number is positive") else: print("The number is negative") else: print("The number is equal to Zero")
Output:
Enter the value of number=-90
The number is negative
Example 2
number1=int(input("Enter the value for First number=")) number2=int(input("Enter the value for Second number=")) number3=int(input("Enter the value for Third number=")) if(number1<number2): if(number1<number3): print("The first number is smallest") else: print("The third number is smallest") else: if(number2<number3): print("The second number is smallest") else: print("The third number is smallest")
Output:
Enter the value for First number=90
Enter the value for Second number=50
Enter the value for Third number=100
The second number is smallest
Leave a comment