L2·Control & Collections
🧩match / case (Pattern Matching)
Structural pattern matching added in Python 3.10.
matchcase3.10patterns
§ 1Basics
match compares a value against case patterns top to bottom and runs the first that fits. _ is the wildcard (like 'default').
1match status:2 case 200: print("OK")3 case 404: print("Not found")4 case _: print("Other")§ 2Destructuring
Patterns can unpack sequences and dicts and bind names at the same time.
1match point:2 case (0, 0): print("origin")3 case (x, 0): print("on x axis at", x)4 case (x, y): print(x, y)§ 3Guards and OR
Add if after a pattern for extra conditions; | combines alternatives: case 'y' | 'yes':
Worked example
1def handle(cmd):2 match cmd.split():3 case ["go", direction]:4 return f"moving {direction}"5 case ["pick", *items] if items:6 return f"picked {', '.join(items)}"7 case ["quit" | "exit"]:8 return "bye"9 case _:10 return "unknown"1112for c in ["go north", "pick key lamp", "exit", "dance"]:13 print(handle(c))Try it live · Python runs in your browser
Loading playground…
ChallengeWrite a calculator using match on (a, op, b) tuples.
Checkpoint quiz
Question 1 / 2
The wildcard pattern is:
Lesson test
Take an 8-question test on “match / case (Pattern Matching)” — concepts, output prediction, bug spotting and interview questions.