Python Tutorial · Control Flow · Lesson 20 of 42
Python Match Statement
Structural pattern matching with match/case (Python 3.10+).
match / case
match compares a value against patterns — like switch in other languages, but more powerful.
def http_status(code):
match code:
case 200 | 201:
return "OK"
case 404:
return "Not found"
case 500:
return "Server error"
case _:
return "Unknown"
print(http_status(201))
print(http_status(418))
Output
OK Unknown
_ is the wildcard that matches anything (the default case). | combines alternatives.
Matching structure
Patterns can unpack sequences and dictionaries and capture parts into variables:
def describe(command):
match command.split():
case ["go", direction]:
return f"Going {direction}"
case ["pick", "up", item]:
return f"Picking up {item}"
case ["quit"]:
return "Bye"
case _:
return "Unknown command"
print(describe("go north"))
print(describe("pick up lamp"))
Output
Going north Picking up lamp
Guards
Add if after a pattern for extra conditions:
def classify(point):
match point:
case (0, 0):
return "origin"
case (x, 0):
return f"on the x-axis at {x}"
case (x, y) if x == y:
return "on the diagonal"
case (x, y):
return f"somewhere else ({x}, {y})"
for p in [(0, 0), (5, 0), (2, 2), (1, 7)]:
print(classify(p))
Output
origin on the x-axis at 5 on the diagonal somewhere else (1, 7)
Test yourself
Which pattern matches any value in a match statement?
*default_else
Show answer
Answer: _