Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Match (match ... case)

When one value decides between many different actions, a long chain of elif lines becomes hard to read. Since version 3.10 Python has the match statement: you name the value once, and each case lists a pattern to compare it with. Python runs the block of the first case that matches. Other languages have a similar switch statement, but Python's match can do more.

Matching values

command = "stop"
match command:
    case "start":
        print("Starting the engine.")
    case "stop":
        print("Stopping.")
    case "pause" | "wait":
        print("Waiting a moment.")
    case _:
        print("Unknown command:", command)
Output
Stopping.

The | sign lists several values in one case. The case with _ matches anything, so it works like else: put it last. Unlike switch in C, there is no falling through to the next case and no break to write: exactly one block runs, or none.

Conditions in a case

A case can add a condition with if, called a guard. A name in a pattern captures the value, so the guard and the block can use it:

for score in [100, 75, 30, -5]:
    match score:
        case 100:
            print(score, "perfect")
        case n if n >= 50:
            print(score, "pass")
        case n if n >= 0:
            print(score, "fail")
        case _:
            print(score, "not a valid score")
Output
100 perfect
75 pass
30 fail
-5 not a valid score

Matching the shape of data

match can also look inside tuples and lists, and take their parts apart at the same time. This is where it is much more powerful than a chain of if statements:

points = [(0, 0), (3, 0), (0, -2), (4, 5)]
for point in points:
    match point:
        case (0, 0):
            print("the 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={x}, y={y}")
Output
the origin
on the x axis at 3
on the y axis at -2
at x=4, y=5

A pattern can be a literal value such as 0, which must be equal, or a name such as x, which accepts any value and stores it. Patterns can also match lists of any length, dictionaries and objects of your own classes.

When to use match

Use match when one value is compared with many fixed values or when data has several possible shapes. For one or two conditions, or conditions on different values, if and elif stay simpler.

Practice exercises

  1. Ask for a day number from 1 to 7 and print the name of the day with match, with a case for invalid numbers.
  2. Write a small calculator: read an operator +, -, * or / and two numbers, and use match on the operator.
  3. Use a guard to print "teenager" for ages 13 to 19.
  4. Match tuples of the form ("move", x, y) and ("quit",) and print what each command means.