Python

Elif and Else Statements

Using alternate cases in Python

What are elif and else statements

Sometimes, if one condition is not met, we want to see if another condition might be met, and if so, we want to run a different bit of code. That’s where "elif’ comes in handy. It’s basically a contraction of "else if". On top of this, sometimes, if none of the conditions are met, we just want the program to run a certain set of alternate commands. This is where ‘else’ comes in handy.

Syntax

It basically looks like this…

if condition1:
	# code for condition1
elif condition2:
	# code for condition2
elif condition3:
	# code for condition3
else:
	# code if none are met

Do note that condition2, condition3, etc will all only be checked if the conditions listed above it are not met (not True). Also, we can have an infinite number of ‘elif’ statements but only one ‘else’ statement per ‘if’ statement. Here is an example working with numbers…

a = 5
b = 6
if a==b:
    print(‘a equals b’)
elif a > b:
    print(‘a is greater than b’)
else:
    print(‘a is less than b’)

Output:

a is less than b

Notice how we used an else statement for if a is less than b. We did this because we know that if we get to the ‘else’ statement, the ‘if’ and ‘elif’ statement must have been False, meaning a had to be less than b. Do note that we can use these statements with any data type. You can use booleans, floats, strings, integers, or even more complex ones you can find on the Official Python Documentation.

chevron_up