Python elif (short for else if) is used to execute a continuous chain of conditional logic ladder.
In elif, there are multiple conditions and the corresponding statement(s) as a ladder. Only one of the blocks gets executed when the corresponding boolean expression evaluates to true.
Syntax of Python elif
The syntax of python elif statement is as shown below.
if boolean_expression_1: statement(s) elif boolean_expression_2: statement(s) elif boolean_expression_3: statement(s) else statement(s)
You can have as many elif statements as required.
Example 1: Python elif
Following is a simple Python elif demonstration. We take two numbers, and have an if-elif statement. We are checking two conditions,
a>b. Which ever evaluates to True, when executed sequentially, the corresponding block is executed.
In the following program,
a<b returns True, and therefore the if block is executed.
a = 2 b = 4 if a<b: print(a, 'is less than', b) elif a>b: print(a, 'is greater than', b) else: print(a, 'equals', b)
2 is less than 4
Example 2: Python elif with multiple elif blocks
As we have already mentioned in the introduction, there can be multiple elif blocks. In the following example, we will write multiple elif blocks in the if-elif ladder.
a = 2 if a<0: print(a, 'is negative') elif a==0: print('its a 0') elif a>0 and a<5: print(a, 'is in (0,5)') else: print(a, 'equals or greater than 5')
2 is in (0,5)
For the given value of a,
a>0 and a<5 is the condition that evaluates to true in the if-elif ladder. Hence, the corresponding block gets executed.
Print this tutorial of Python Examples we learned the syntax of elif statement and how to use it in your Python programs.
Hope this helps!