In this Python tutorial, we will learn about the if-elif conditional statement, its syntax, and how to use it in programming with the help of examples covering some typical use cases.
Python – Elif
Python Elif is a conditional statement in which there could be multiple conditional checks after if block.
Python elif is an extension to Python if-else statement, which we have discussed in our previous tutorial.
Syntax of Python elif
The syntax of Python Else If, elif statement is as shown in the following.
if expression_1: statement(s) elif expression_2: statement(s) elif expression_3: statement(s) else: statement(s)
If expression_1 evaluates to TRUE, then the if-block statements gets executed and the control comes out of the if-elif ladder.
If expression_1 evaluates to FALSE, the control checks expression_2. If expression_2 evaluates to TRUE, statement(s) in the corresponding block are executed. If expression_2 evaluates to False, the control checks expression_3 and so on.
If none of the expressions evaluates to TRUE, then the else-block gets executed. else-block is optional though.
Examples
1. Python Elif Statement
In the following example, we will write a Python elif statement, where we check what is today and do an action based on the day of week.
Python Program
today='Monday' if today=='Sunday': print('eat apple.') elif today=='Monday' or today=='Tuesday': print('eat banana.') elif today=='Wednesday': print('eat cherry.') elif today=='Thursday': print('eat mango.') else: print('eat nothing.')Try Online
Output
eat banana.
2. Python Elif Statement without else block
We already know that else block is optional.
In the following example, we will write a Python elif statement without else block.
Python Program
today='Monday' if today=='Sunday': print('eat apple.') elif today=='Monday' or today=='Tuesday': print('eat banana.') elif today=='Wednesday': print('eat cherry.') elif today=='Thursday': print('eat mango.')Try Online
Output
eat banana.
Conclusion
In this Python Tutorial, we learned Python elif statement: the syntax of elif and how to use it in Python programs with the help of example programs.