Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
If..elif..else Statement

Python if...elif...else Statement

 

if condition1:
    Body of if
 
elif condition2:
    Body of elif
 
else: 
    Body of else

 

The elif is the same as else if in c++ or java. It allows us to check for multiple expressions.

If the condition for if is False, it checks the condition of the next elif block and so on.

If all the conditions are False, the body of else is executed.

Only one block among the several if...elif...else blocks is executed according to the condition.

The if a block can have only one else block. But it can have multiple elif blocks.

 

 

Example:

 

 

#find the largest among three number
a = 5
b = 6
c = 4
 
if a >= b and a >= c:
    print("a is greater")
    
elif b >= c and b >= a:
    print("b is greater")
    
else:
    print("c is greater")

 

output: 

 

b is greater