In Python, elif is short for "else if" and is used when the first if statement isn't true, but you want to check for another condition. Meaning, if statements pair up with elif and else statements to perform a series of checks.
A full if/elif/else block is in the code example below.
player_age = 12
if player_age >= 18:
print("You could be in college.")
elif player_age >= 13:
print("You can also attend iD Academies!")
elif player_age >= 7:
print("You can attend iD Tech Camps!")
else:
print("You're young.")
When you run the code and input multiple ages, you can see which part of the if/elif/else block prints out.
Using the example above, if and elif statements always look for a specific condition:
- if player_age > 18 : #Happens if the age is greater than 18.
- elif player_age > 13 : #Only happens if the age is not greater than 18 and greater than 13.
An else statement doesn't look for a specific condition. Else statements occur after an if or elif statement in your code.
- if player_age > 18 : #Happens if the age is greater than 18.
- else : #Would happen for any other age not specified above.
Every if/elif/else block must begin with one regular if statement and end with a single else statement, but you can have as many elif statements in the middle as you want!
Need help? See elif in action in this Python "guess the number" game tutorial. Or, check out our live instruction either in-person at our Python summer camps or virtually with our online Python tutoring.