Skip to content
Kuza Ndoto Academy

Match-Case

Beginner → IntermediateChapter 3 · Page 14 of 564 min readUpdated 15 Nov 2026

The match statement, added in Python 3.10, compares a value against a series of patterns and runs the code for the first one that fits. For simple cases it replaces long if/elif chains, and its pattern matching can also pull values apart, which if can't do as neatly.

Basic syntax

Write match followed by the value to check, then one case block per pattern. Python tries each case from top to bottom and runs only the first match.

command = "balance"

match command:
    case "send":
        print("Send money")
    case "balance":
        print("Check balance")
    case "airtime":
        print("Buy airtime")
    case _:
        print("Unknown command")
Check balance

The underscore _ is a wildcard: it matches anything, so it works like else. Put it last. If no case matches and there's no wildcard, the match statement simply does nothing.

Note

match needs Python 3.10 or newer. Unlike the switch statement in languages such as C or Java, there is no "fall-through" and no break is needed: once a case runs, the whole match is finished.

Matching several values with |

The | symbol means "or" inside a pattern. Add as name to capture which option actually matched.

day = "Sat"

match day:
    case "Sat" | "Sun":
        print("Weekend: rest and revise")
    case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
        print("Weekday: classes")
    case _:
        print("That's not a day")

reply = "exit"
match reply:
    case "quit" | "exit" as word:
        print(f"You typed '{word}'. Goodbye!")
Weekend: rest and revise You typed 'exit'. Goodbye!

Adding conditions with guards

A guard is an if added to a case. The case only matches when the pattern fits and the guard is true. Writing a plain name, such as t, as the pattern captures the value into that variable so the guard can test it.

temperature = 31

match temperature:
    case t if t >= 30:
        print(f"{t}°C: hot, drink plenty of water")
    case t if t >= 18:
        print(f"{t}°C: pleasant")
    case t:
        print(f"{t}°C: carry a sweater")
31°C: hot, drink plenty of water

For pure range checks like this one, an if/elif chain is equally good. Guards shine when combined with the structural patterns below.

Matching structure: sequences

This is where match becomes really powerful. A pattern can describe the shape of a value. Here, split() turns the user's text into a list of words, and each case checks how many words there are and what they say, capturing the parts it needs.

text = "send 500 0712345678"

match text.split():
    case ["send", amount, phone]:
        print(f"Sending KES {amount} to {phone}")
    case ["balance"]:
        print("Your balance is KES 2,300")
    case ["help", *topics]:
        print("Help requested on:", topics)
    case _:
        print("Sorry, I didn't understand that")
Sending KES 500 to 0712345678

The first case matches a list of exactly three items whose first item is "send", and stores the second and third items in amount and phone. Change text to "balance" and the second case runs. Change it to "help pin airtime" and the third case runs: *topics collects any remaining words, printing Help requested on: ['pin', 'airtime'].

The same idea works for pairs of values written in round brackets (called tuples):

point = (0, 5)

match point:
    case (0, 0):
        print("At the origin")
    case (0, y):
        print(f"On the y-axis at {y}")
    case (x, 0):
        print(f"On the x-axis at {x}")
    case (x, y):
        print(f"At ({x}, {y})")
On the y-axis at 5

You can also match dictionaries by their keys and objects by their class, but sequence and literal patterns cover most everyday needs.

match or if/elif?

Use match-case when…Use if/elif when…
You compare one value against many fixed optionsConditions involve different variables
You need to unpack the structure of a value (commands, coordinates)You mainly test ranges such as marks >= 80
Your code must run on Python 3.10+ anywayYour code must also run on older Python versions
Common mistake

Using a plain variable name as if it were a constant. In a pattern, a bare name like RED doesn't compare against a variable called RED; it captures any value into a new variable with that name. So case RED: matches everything, and Python refuses to run the code with SyntaxError: name capture 'RED' makes remaining patterns unreachable if other cases follow it. Use literal values such as case "red":, or dotted names such as case Colour.RED:.

Common mistake

Putting case _: anywhere but last. Because it matches everything, any cases after it could never run, and Python reports a SyntaxError.

Key points

  • match value: checks case patterns from top to bottom and runs the first that fits; there is no fall-through.
  • case _: is the catch-all wildcard and must come last.
  • | combines alternatives, as captures the match and if adds a guard.
  • Sequence patterns such as ["send", amount, phone] check structure and unpack values at once.
  • Bare names in patterns capture values; use literals or dotted names for constants.
Up next · Control FlowWhile LoopsRepeat code while a condition is true.
→

Tip: use the ← and → keys to move between pages.