match and case
Picking a branch by matching a value against patterns.
5 minute read
Big idea
match compares one value against a list of patterns and runs the first case that fits — a tidy replacement for a long chain of elif x == ....
The idea
day = 3
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case _:
print("Some other day")output
WednesdayRun and edit it in the app.
match day:— the value to check.case 3:— "if it's 3, run this".case _:— the wildcard: matches anything. Put it last, as the "otherwise".
Only one case runs, and there's no "falling through" to the next case as in C's switch — no break needed.
(match arrived in Python 3.10. Older Pythons don't have it; there you'd write if/elif.)
Several values in one case
| means "or" inside a pattern:
day = "sat"
match day:
case "sat" | "sun":
print("Weekend")
case "mon" | "tue" | "wed" | "thu" | "fri":
print("Weekday")
case _:
print("Not a day")What does it print? Show the answer
WeekendRun and edit it in the app.
Watch it
Patterns with a condition
Add if after a pattern for an extra check — called a guard. A plain name like n matches anything and captures it:
for n in [-4, 0, 7]:
match n:
case 0:
print("zero")
case n if n < 0:
print("negative")
case _:
print("positive")output
negative
zero
positiveRun and edit it in the app.
Matching shapes
match really shines when the value has a structure, like a list of words. Each pattern can pull the pieces out:
for command in ["go north", "look", "take lamp", "dance"]:
match command.split():
case ["go", direction]:
print("You walk", direction)
case ["look"]:
print("You see a dark room")
case ["take", item]:
print("You pick up the", item)
case _:
print("I don't understand")output
You walk north
You see a dark room
You pick up the lamp
I don't understandRun and edit it in the app.
["go", direction] matches a two-word list whose first word is "go", and stores the second word in direction. (Lists get their own module next — this is a preview of why they're useful.)
day = 5
match day:
case _:
print("Unknown day")
case 5:
print("Friday")output
FridayRun and edit it in the app.
The wildcard matches everything, so a case after it can never run. Python actually refuses this with a SyntaxError: wildcard makes remaining patterns unreachable. Move case _ to the end.
What does case _ match?
Think of it like
A post-office sorting desk. Each parcel is checked against the labels on the bins — "London", "Paris", "anything else" — and goes into the first bin that matches.
Key terms
- match / case — Compare a value against patterns; run the first case that fits.
- Wildcard (
_) — A pattern that matches anything. - Guard — An
ifcondition attached to a case.
Check yourself
Where should case _ go?
What does case "a" | "b": match?
Unlike C's switch, does a Python case fall through to the next?