← Python lessons

Python match case: Python's Switch Statement

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A match statement compares one value against a list of case patterns and runs the first one that fits. It can replace a long if/elif chain of == checks.

Read if, elif, else first. match needs Python 3.10 or newer.

Match one value against fixed options

choice = "2"
match choice:
    case "1":
        print("Start game")
    case "2":
        print("Show scores")
    case _:
        print("Unknown option")

This prints Show scores. case _: is the wildcard: it matches anything, so it works like else. Only the first matching case runs.

The same menu as an if chain:

choice = "2"
if choice == "1":
    print("Start game")
elif choice == "2":
    print("Show scores")
else:
    print("Unknown option")

Several options in one case

Join options with | to give them the same branch.

answer = "Y"
match answer:
    case "y" | "Y" | "yes":
        print("Saving")
    case "n" | "N" | "no":
        print("Not saved")
    case _:
        print("Please answer y or n")

This prints Saving.

Match the shape of a list

A case can unpack a list and capture its parts into names.

for command in [["move", 3], ["say", "hi"], ["quit"], ["jump", 1, 2]]:
    match command:
        case ["move", steps]:
            print("Moving", steps)
        case ["say", text]:
            print("Saying", text)
        case ["quit"]:
            print("Bye")
        case _:
            print("Bad command:", command)

["move", steps] matches a two-item list starting with "move" and stores the second item in steps. ["jump", 1, 2] fits no pattern, so the wildcard runs.

When to use if instead

A bare name in a case captures the value. It does not compare against a variable. This catches people out:

LIMIT = 20
battery = 75
match battery:
    case LIMIT:
        print("matched, and LIMIT is now", LIMIT)

This prints matched, and LIMIT is now 75. To compare with a range such as battery <= 20, use if/elif, or add a guard: case n if n <= 20:. Use match for fixed values and list shapes; use if for comparisons.

See also: Unpacking Values, Lists.

Your turn

Use match to turn each day into a message: "sat" or "sun" prints Weekend, "mon" prints Back to school, and anything else prints Weekday.

days = ["sat", "mon", "wed", "sun"]
# loop over days and match each one: sat or sun, mon, then the wildcard

Expected output

Weekend
Back to school
Weekday
Weekend