Control flowChapter 43 of 114
If...Else
Run code only when a condition holds, and choose between branches.
if
A condition, a colon, and an indented block:
temperature = 31
if temperature > 30:
print("Hot")
print("Always runs")Output
Hot Always runs
The condition does not have to be a comparison. Any value works, judged by the truthiness rules: empty and zero are false, everything else is true.
items = []
if items:
print("we have items")
if not items:
print("nothing here")Output
nothing here
else
age = 15
if age >= 18:
print("Can vote")
else:
print("Too young")Output
Too young
elif
Use elif for the second and later conditions. Only the first true branch runs:
score = 72
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "F"
print(grade)Output
B
Order matters. Put the narrowest condition first, or a broader one will catch everything before it gets there:
score = 95
if score >= 50:
grade = "C"
elif score >= 90:
grade = "A"
print(grade)Output
C
The elif never gets a chance. That is a logic bug, and Python cannot warn you.
Combining conditions
age = 25
member = True
if age >= 18 and member:
print("Full access")
if age < 13 or age > 65:
print("Discount")
else:
print("Standard price")Output
Full access Standard price
Chained comparisons read better than two clauses joined by and:
age = 25
print(18 <= age < 65)Output
True
The conditional expression
When both branches only assign one value, this one-liner is clearer than four lines:
age = 15
status = "adult" if age >= 18 else "minor"
print(status)Output
minor
Keep it to one condition. Nested conditional expressions are hard to read and a normal if is right there.
Nesting
logged_in = True
admin = False
if logged_in:
if admin:
print("Admin panel")
else:
print("User dashboard")
else:
print("Please log in")Output
User dashboard
def describe(age):
if age < 0:
return "not a real age"
if age < 18:
return "minor"
return "adult"
print(describe(-1), describe(10), describe(30))Output
not a real age minor adult
An empty branch needs pass
value = 5
if value > 3:
pass
else:
print("small")
print("done")Output
done
Test yourself
2 questionsWhy does this give C for a score of 95? if score >= 50: grade = "C" elif score >= 90: grade = "A"
Show the answer
The first condition is true, so the elif never runs — Only the first true branch runs, so the narrowest condition has to come first.
What does 'if items:' test for a list?
Show the answer
Whether it has anything in it — An empty list is falsy, which is why this is preferred over len(items) > 0.
Match
Structural pattern matching, and where it beats a chain of elif.