Syllabus Lesson 16 of 239 · Control Flow
Control Flow

Multi-way Branching with match / case

When you are checking one value against many fixed options, a long if / elif chain works but can get noisy. Python's match statement (added in 3.10) reads cleanly for that job.

You match a value, then list case patterns. The first matching case runs. The underscore _ is the catch-all, like else:

def describe(day):
    match day:
        case "sat":
            return "weekend"
        case "sun":
            return "weekend"
        case _:
            return "weekday"

print(describe("sun"))   # weekend
print(describe("mon"))   # weekday

One case can match several values with | (read it as "or"):

def kind(status):
    match status:
        case 200 | 201 | 204:
            return "ok"
        case 404 | 410:
            return "missing"
        case _:
            return "other"

print(kind(404))   # missing

You can even add a condition to a case with if, called a guard:

def sign(n):
    match n:
        case 0:
            return "zero"
        case _ if n > 0:
            return "positive"
        case _:
            return "negative"

For one-value-to-many-outcomes branching, match is often the most readable choice.

Your turn

Define a function http_label(code) using a match statement. Return "ok" for 200 or 201, "redirect" for 301 or 302, "not found" for 404, and "unknown" for anything else (use _). Combine values in one case with |.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output