Python — Match
switch's cooler Python cousin
match compares a value against patterns and runs the first matching block (Python 3.10+):
command = "start"
match command:
case "start":
print("Starting…")
case "stop":
print("Stopping")
case _:
print("Unknown command") # _ = default/catch-all
Capture patterns — match into a variable
A bare name matches ANYTHING and binds it:
match point:
case (0, 0):
print("origin")
case (x, y): # captures both parts
print(f"at {x}, {y}")
That example also shows sequence unpacking — match works on lists/tuples by shape, not just equality.
Or-patterns
Several alternatives, one body:
match key:
case "q" | "quit":
running = False
case "h" | "help":
show_help()
Guards — extra conditions with if
match score:
case n if n >= 90:
grade = "A"
case n if n >= 80:
grade = "B"
case _:
grade = "F"
The guard decides; the capture names the value.
Destructuring objects
Match can reach inside dicts and class instances:
match user:
case {"role": "admin", "name": name}:
print(f"Admin {name}")
case {"role": role, "name": name}:
print(f"{role}: {name}")
Class patterns check type + fields:
match event:
case Click(x=x, y=y):
print(f"click at {x},{y}")
case KeyPress(key="Enter"):
submit()
match vs if/elif
| Use match when | Use if/elif when |
|---|---|
| One value against many shapes/literals | conditions involve different variables |
| Destructuring structures | simple range checks |
| Command parsers, state machines | quick two-way branches |
Ranges need guards (if n >= 90), so plain number grading is often clearer as if/elif — match shines on structure.
Gotchas: requires Python ≥ 3.10 · bare
case x:before later cases swallows everything (it's a catch-all!) ·_matches without binding.
Mini Practice
- Command parser: start/stop/help/quit via or-patterns.
- Tuple matcher distinguishing 2D origin, axes, general points.
- Dict pattern routing API payloads by "type".
- Guard-based HTTP status handler (2xx/4xx/5xx).
- Rewrite an if/elif tower as match — judge readability honestly.
Next: while loops →
Related Topics
Frequently Asked Questions about Match
What is Match in Python?
Match is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Match?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Match.
Why is Match important in Python?
Match is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.