Python Elif Statement - Syntax, Examples


Python elif

Python elif (short for else if) is used to execute a continuous chain of conditional logic ladder.

https://youtu.be/hkzm_L_4GSE?si=ipp2xYwxQsu9dKC8

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

Examples

1. A simple elif example

The following is a simple Python elif demonstration. We take two numbers, and have a If-elif statement. We are checking two conditions: a<b in if-condition and a>b in elif-condition.

First, if-condition is checked, and then elif-condition is checked. elif-condition is checked only when if-condition is False.

In the following program, for given values of a and b, a<b returns False, and a>b returns True. Therefore the elif block executes.

Python Program

a = 6
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)

Output

6 is greater than 4

2. Multiple elif blocks

We have already learnt in the introduction that there can be multiple elif blocks. In the following example, we write multiple elif blocks in the if-elif ladder.

Python Program

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')

Output

2 is in (0,5)

For the given value in variable a, a>0 and a<5 is the condition that evaluates to true in the if-elif ladder. Therefore, the corresponding block gets executed.

Summary

In this tutorial of Python Examples, we learned the syntax of elif statement and how to use it in your Python programs.