Split the decision. Again.
The problem...
You have if. You have else. Two options — true or false, yes or no.
But reality rarely works in two options. A grade isn't just pass or fail. A temperature isn't just hot or not hot. A user isn't just logged in or not.
Sometimes there are three options. Five. Ten.
The idea!
Between if and else, you can add as many conditions as you need. That's elif — short for "else if".
Check the first condition. If it fails, check the next. And the next. Until one matches — or none do.
The syntax
if condition_1:
# runs if condition_1 is True
elif condition_2:
# runs if condition_1 is False and condition_2 is True
elif condition_3:
# runs if condition_1 and condition_2 are False and condition_3 is True
else:
# runs if nothing above matched
Python checks from top to bottom. The first condition that's true — that block runs. Everything else is skipped.
Your first elif
score = 72
if score >= 90:
print("Excellent.")
elif score >= 70:
print("Good.")
elif score >= 60:
print("Passed.")
else:
print("Failed.")
Score is 72 — first condition fails, second matches. "Good." prints. The rest are never checked.
Order matters
# Wrong order — broken logic
score = 95
if score >= 60:
print("Passed.") # this always runs first
elif score >= 90:
print("Excellent.") # never reached
# Correct order — most specific first
if score >= 90:
print("Excellent.") # checked first
elif score >= 60:
print("Passed.") # only if above failed
Always put the most specific condition first. Python stops at the first match.
elif without else
temperature = 20
if temperature > 35:
print("Very hot.")
elif temperature > 25:
print("Warm.")
elif temperature > 15:
print("Comfortable.")
else is optional. If no condition matches and there's no else — nothing runs. No error.
Heads up!
elifis always betweenifandelse— never alone- Python stops at the first matching condition — the rest are skipped
- Order matters — most specific conditions go first
- You can have as many
elifblocks as you need elseat the end is optional, but recommended
The mindset shift
Stop thinking: "I have two options — true or false."
Start thinking: "I have as many options as the problem needs."
What you should understand now
elifadds more conditions betweenifandelse- Python checks conditions top to bottom — first match wins
- Order matters — always put the most specific condition first
- You can chain as many
elifblocks as needed elseat the end catches everything that didn't match