Lesson 5 of 5 · Control Flow · 3 min read · Updated

match: choosing between many cases

A cleaner alternative to long if-elif chains, which can also look inside values.

When one value decides between many branches, match (Python 3.10 and later) reads more clearly than a stack of elifs.

python
for command in ["start", "stop", "pause", "jump"]:
    match command:
        case "start":
            print("Starting")
        case "stop" | "pause":
            print("Stopping")
        case _:
            print("Unknown:", command)
Output
Starting
Stopping
Stopping
Unknown: jump
  • Cases are tried top to bottom; the first that fits runs, and no other.
  • | means "or": one case for several values.
  • case _: matches anything — the "otherwise" branch. Put it last.

Looking inside a value

python
for point in [(0, 0), (3, 0), (0, 5), (2, 7)]:
    match point:
        case (0, 0):
            print("Origin")
        case (x, 0):
            print(f"On the x axis at {x}")
        case (0, y):
            print(f"On the y axis at {y}")
        case (x, y):
            print(f"At {x}, {y}")
Output
Origin
On the x axis at 3
On the y axis at 5
At 2, 7

This is where match goes beyond if. A case can describe the shape of a value; names in the pattern such as x capture the parts, ready to use in that branch.

Adding a condition

python
for marks in [95, 72, 30]:
    match marks:
        case m if m >= 90:
            print(m, "Distinction")
        case m if m >= 50:
            print(m, "Pass")
        case _:
            print(marks, "Fail")
Output
95 Distinction
72 Pass
30 Fail

Warning

A bare name in a case always matches and captures — it does not compare. case limit: does not mean "equal to the variable limit"; it matches everything and overwrites limit. Compare with a guard instead: case v if v == limit:.

In a match, what does case _: do?

Try this now

  1. Ask for a day name and use match to print "Weekend" for Saturday or Sunday and "Weekday" otherwise.
  2. Write a tiny calculator: ask for two numbers and an operator (+ - * /) and match on the operator.

Create a free account to save your progress, or sign in.