if, elif, else
Running code only when a condition is True.
5 minute read
Big idea
if runs a block of code only when a condition is True. elif and else add other paths, and Python takes exactly one of them.
The idea
if condition:
# runs only when condition is True
Two things matter: the colon at the end of the if line, and the indentation (4 spaces) of the lines that belong to it. That indented group is called a block. When the indentation stops, the block is over.
temperature = 31
if temperature > 30:
print("It's hot!")
print("Drink some water.")
print("Have a nice day.")output
It's hot!
Drink some water.
Have a nice day.Run and edit it in the app.
The last print isn't indented, so it runs no matter what.
else: the other path
if age >= 18:
print("You can vote.")
else:
print("Not yet!")
elif: more than two paths
elif (short for "else if") checks another condition. Python tests each one top to bottom and runs the first that's True — then skips the rest.
score = 82
if score >= 90:
print("A")
elif score >= 75:
print("B")
elif score >= 50:
print("C")
else:
print("F")What does it print? Show the answer
BRun and edit it in the app.
82 is also >= 50, but that check never happens — the elif score >= 75 branch already ran.
Watch it
Order matters
score = 95
if score >= 50:
print("Pass")
elif score >= 90:
print("A")
else:
print("Fail")output
ARun and edit it in the app.
Put the most specific test first: score >= 90 before score >= 50.
Nesting and combining
A block can contain another if. Often and/or reads better than nesting:
if has_ticket:
if age >= 18:
print("Welcome")
if has_ticket and age >= 18: # same thing, flatter
print("Welcome")
A one-line choice
For picking between two values, there's a compact form called a conditional expression:
label = "even" if n % 2 == 0 else "odd"
x = 10. Which line prints? if x > 5: print('A') elif x > 8: print('B') else: print('C')
Think of it like
A fork in a path with signposts. You read the signs in order and take the first one that matches you. else is the path for everyone else.
Common mistake
Forgetting the colon, or mixing indentation:
if x > 5 # ✗ SyntaxError: expected ':'
print("big")
Key terms
- Condition — An expression that's True or False.
- Block — The indented lines that belong to an
if, loop, or function. - elif — "Otherwise, if…": another condition to check.
Check yourself
What marks the lines that belong to an if?
In an if/elif/else chain, how many branches run?
What ends the if line?