The elif
is short for else if. It allows us to check for multiple expressions.
if…elif…else
are conditional statements that provide you with the decision making that is required when you want to execute code based on a particular condition. When you run into a situation where you have several conditions, you can place as many elif
conditions as necessary between the if
condition and the else
condition.
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.
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.
Syntax:
>>>if (condition):
Statement
>>>elif(condition):
Statement
>>>else(condition):
Statement
Flow Chart:
Example:
x = 5
if x % 2 == 0:
print('x is divisible by 2')
elif x % 3 == 0:
print('x is divisible by 3')
else:
print('x is neither divisible by 2 nor by 3 ')
Output:
x is neither divisible by 2 nor by 3