if / elif / else & match
Making decisions
if condition:
...
elif other_condition:
...
else:
...
- Python checks from top to bottom and runs only the first matching block.
- The block is defined by indentation and a colon
:ends each header line.
Conditional (ternary) expression
status = "adult" if age >= 18 else "minor"
Truthiness in conditions
if items: is the Pythonic way to say "if the list is not empty".
match / case (Python 3.10+)
A clean way to compare one value against many patterns:
match command:
case "start": ...
case "stop" | "quit": ...
case _: ... # anything else
⚠️ Common mistakes
- Using
=instead of==in a condition - Writing
if x == 1 or 2:(always true!). Writeif x == 1 or x == 2:orif x in (1, 2):
▶️ Runs in the app.
Example
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade) # B
age = 17
print("adult" if age >= 18 else "minor") # minor
command = "quit"
match command:
case "start":
print("Starting…")
case "stop" | "quit":
print("Goodbye!") # Goodbye!
case _:
print("Unknown command")