Python provides the
if statement in order to branch the code according to the different conditions. The
elif statement is used to add extra conditions and branches to the code by checking new conditions. The
elif is the short form of the
else if statement to make things simpler. In this tutorial we examine what is elif statement and how can we use the elif statement in Python.
elif Statement Syntax
The elif statement syntax is like the below which is used after the if statement. We can use the elif statement single or multiple times according to the situation.
if CONDITION1: CODE_BLOCK1 elif CONDITION2: CODE_BLOCK2 elif CONDITION3: CODE_BLOCK3 ... else: CODE_BLOCKN
- CONDITION’s are related to branch conditions to check.
- CODE_BLOCK’s are related branch code block which is executed when the related CONDITION is true.
elif Statement Usage
We can use the elif statement to check multiple conditions after the if statement. In the following example, we check the age by using multiple elif statement.
age = 21 if age>80: print("Age is over 80") elif age>65: print("Age is over 65") elif age>18: print("Age is over 18") elif age>12: print("Age is over 12")