if / elif / else
beginner12 min readLesson 13 of 169
Branching: conditions, blocks, and the first-true-branch-wins rule.
Programs get interesting when they choose. The if statement runs a block only
when its condition is True:
temperature = 31
if temperature > 30:
print("It's hot!")
print("Drink water")
print("(always printed)")
The colon + indentation rule
The : ends the condition line. Every line that belongs to the decision is
indented (4 spaces by convention). Dedenting closes the block. Indentation is
not decoration in Python โ it is the grammar.
if temperature > 30:
print("hot") # inside the if
print("done") # outside โ always runs
else and elif
if score >= 50:
print("pass")
else:
print("fail")
For many mutually exclusive cases, elif chains read top to bottom and the
first true branch wins:
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
Note the order: checking score >= 70 first would give wrong grades โ with
elif, put the most specific (highest) threshold first.