Flow controls: Conditions · 7 / 22 Theory

The match/case statement

Since Python 3.10 there is the match statement, which compares a value against a series of patterns and runs the first one that fits. It resembles the switch of other languages but is far more powerful: it does not only compare values, it also takes structures apart (lists, tuples, dictionaries, objects) and captures their parts into variables.

Literal and structural patterns

Each case describes a shape. If the value fits it, the pattern’s variables are filled in and the block runs. The _ pattern is the wildcard: it matches everything, which is why it goes last.

command = "move north".split()

match command:
    case ["stop"]:
        print("Stopped")
    case ["move", direction]:           # captures the second element
        print("Moving towards", direction)
    case ["move", direction, steps]:
        print("Moving", steps, "steps towards", direction)
    case _:                              # wildcard: anything else
        print("Unknown command")

Options, guards and wildcard

With | a single case accepts several alternatives. With if you add a guard: the pattern is only accepted if that extra condition also holds.

def classify(code):
    match code:
        case 200 | 201 | 204:            # several options with |
            return "ok"
        case 404:
            return "not found"
        case n if 500 <= n < 600:        # guard: extra condition with if
            return "server error"
        case _:
            return "other"

print(classify(201))   # ok
print(classify(503))   # server error
print(classify(302))   # other

Unpacking tuples

point = (3, 0)

match point:
    case (0, 0):
        print("Origin")
    case (x, 0):
        print("On the X axis, x =", x)
    case (0, y):
        print("On the Y axis, y =", y)
    case (x, y):
        print("Point", x, y)

Note that (x, 0) does not compare against the variable x: it captures the first element in a new variable called x. To compare with a specific value, use literals or dotted names (for example Color.RED).

Summary of patterns

# Sketch of the syntax (illustrative only)
match value:
    case 0:                      # literal
        ...
    case "a" | "b":              # several literals
        ...
    case [a, b]:                 # list or tuple of 2 elements
        ...
    case [first, *rest]:      # first and the rest
        ...
    case {"kind": t}:            # dictionary with the key "kind"
        ...
    case int(n):                 # checks the type
        ...
    case _:                      # wildcard
        ...
  • match evaluates the case clauses in order and stops at the first that fits; no break is needed.
  • A bare name in a pattern always captures, it never compares.
  • If no case fits and there is no _, nothing happens.
  • To compare a value against simple constants, if/elif is still perfectly valid; match shines when there is structure.

You practice it in Menu with match, and classic conditions in Leap year, Classifying a triangle and Shipping rate by brackets.