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.

Syntax of Python elif

Following is the syntax of Python Else If, elif statement.

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.

Example 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.

example.py – Python Program

today='Monday'

if today=='Sunday':
	print('Do nothing.')
elif today=='Monday' or today=='Tuesday':
	print('Clean the floor.')
elif today=='Wednesday':
	print('Prepare chicken.')
elif today=='Thursday':
	print('Visit Library.')
else:
	print('Go for excercise.')
Try Online

Output

Clean the floor.

Example 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.

example.py – Python Program

today='Monday'

if today=='Sunday':
	print('Do nothing.')
elif today=='Monday' or today=='Tuesday':
	print('Clean the floor.')
elif today=='Wednesday':
	print('Prepare chicken.')
elif today=='Thursday':
	print('Visit Library.')
Try Online

Output

Clean the floor.

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.