Python match Statement
In this page:
Basic Match-Case
Introduced in Python 3.10, match/case compares one value against a series of patterns and runs the block for the first match — it reads more like a lookup table than an elif ladder, especially once you're checking more than two or three cases.
Example: Basic Match-Case
command = "start"
match command:
case "start":
print("Starting")
case "stop":
print("Stopping")
Wildcard Fallback (case _)
The underscore _ acts as a catch-all pattern that always matches, functioning exactly like the final else in an if/elif ladder — Python's linter will also warn you if a match block is missing one and could fall through with no match.
Example: Wildcard Fallback (case _)
command = "pause"
match command:
case "start":
print("Starting")
case _:
print("Unknown command")
Grouping Cases with |
The | operator inside a case groups multiple values that should trigger the same block, like case "y" | "yes":, avoiding the need for separate, duplicate cases that do identical work.
Example: Grouping Cases with |
answer = "y"
match answer:
case "y" | "yes":
print("Confirmed")
case _:
print("Not confirmed")
Match-Case with Guards
Adding an if clause after a pattern — called a guard — lets a case match only when both the pattern *and* an extra condition hold, such as case n if n > 0:, combining structural matching with an ordinary boolean check.
Example: Match-Case with Guards
n = 5
match n:
case n if n > 0:
print("Positive")
case _:
print("Not positive")
Matching Sequences
Beyond simple value matching, match can destructure sequences directly in the pattern — case [x, y]: binds x and y to a two-element list's contents in one line, something an elif ladder can't express nearly as cleanly.
Example: Matching Sequences
point = [3, 4]
match point:
case [x, y]:
print(x, y)
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: