If, Elif, Else and Nested If:
In Python, we have 3 types of statements for decision-making – The Python if...elif...else statements
Elif is short for Else if, and it allows us to check multiple expressions. In case the current Elif returns False , the condition passes to the next elif, until any one of the elif returns True
If none of the Elif returns True, the statement in Else would be run
But, in case, if any of the if or elif returns True, the else statement will not be run.
Syntax:
if condition:
statement1
elif condition:
statement2
else:
statement3
Working:
‘If’ Condition returned True:
The statement within the if (statement1) will be executed, and Python will not read elif and else statements
Output: statement1
‘Elif’ Condition returned True:
The statement within the if (statement1) will not be executed, and the condition passes to elif.
Since the elif condition returns True, statement2 will be executed.
Output: statement2
‘Else’ Condition returned True:
Python will not execute the statement within the if (statement1), and the condition passes to elif.
The elif condition now returns False, statement2 will not be executed.
Since If and Elif both returned False, the Else statement will be executed in no condition
Output: statement3
Example for If, Elif and Else Statements:
#Code to check whether num is a 2-Digit number or not
num= 14
if num<10:
print("num is a 1-digit number ")
elif num>99:
print("num is a 3-digit number ")
else:
print("num is a 2-digit number ")
print("Since this is outside the if...elif...else statements, this will be executed all the time!")
When you run the program, the output will be:
num is a 2-digit number
Since this is outside the if...elif...else statements, this will be executed all the time!
Nested If:
if condition-a:
if condition-b:
statement1
elif condition-c:
statement2
else:
statement3
else:
statement4
Here, python reads lines 2-9, only if condition-a returns True
If condition-a was True, Python goes in and reads condition-b and so on.
If condition-a was False, then Python will not even read condition-b, condition-c and else.
This means that, even in any case either condition-b or condition-c returned True, since condition-a turns out to be False
In this case, else statement will be executed and the Program ends.
Example for Nested If:
#Here, we check if num is Positive, negative or Zero using Nested If
num = int(input("Number: "))
if num >= 0:
if num == 0:
print("Num is neither Positive nor Negative, Zero")
else:
print("Num is a Positive number")
else:
print("Num is a Negative number")
Output1:
Number: 10
Num is a Positive number
Output2:
Number: 0
Num is neither Positive nor Negative, Zero
Output3:
Number: -4
Num is a Negative number
Conclusion:
Now you must be having a clear idea on Python If Else Elif and Nested if Statements. If you are on your way to become a Pythonista, you might find our site really helpful. Hit this link for more python related posts
Check it out, it’s Simply the Best Code.