</>
Skip to content
Python lessons (18/45)

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 whenUse if/elif when
One value against many shapes/literalsconditions involve different variables
Destructuring structuressimple range checks
Command parsers, state machinesquick 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

  1. Command parser: start/stop/help/quit via or-patterns.
  2. Tuple matcher distinguishing 2D origin, axes, general points.
  3. Dict pattern routing API payloads by "type".
  4. Guard-based HTTP status handler (2xx/4xx/5xx).
  5. 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.