Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 03 / Topic 4 of 12

match / case

match compares one value against many patterns (shapes the value can match). It works like a phone menu: "press 1 for balance, press 2 for an agent". It is cleaner than a long if/elif chain on the same variable. Only the first matching case runs.

Pattern Example Meaning
Literal case "red": value equals "red"
OR pattern case "sat" | "sun": equals any of them
Wildcard case _: anything else (like else)
Capture case x: store the value in x
Guard case x if x > 100: capture, then check an extra condition

Real-world example: a traffic signal and food-delivery ratings.

signal = "yellow"

match signal:
    case "red":
        action = "Stop"
    case "yellow" | "amber":
        action = "Slow down"
    case "green":
        action = "Go"
    case _:
        action = "Signal broken, drive carefully"

print(action)  # Slow down

for stars in [5, 3, 2, 9]:     # `for` repeats for each rating: see section 6 (lists: Part 4)
    match stars:
        case 5:
            review = "Excellent"
        case 4 | 3:
            review = "Good"
        case n if n < 1 or n > 5:      # capture into n, then check the guard
            review = f"{n} is not a valid rating"
        case n:
            review = f"Sorry ({n} stars)"
    print(review)
# Excellent
# Good
# Sorry (2 stars)
# 9 is not a valid rating

match needs Python 3.10+. A bare name like case n: (or the wildcard case _:) matches anything, so it must be the last case. If you put another case after it, Python refuses to run the file: SyntaxError: name capture 'n' makes remaining patterns unreachable.

๐Ÿ” Going deeper: match is structural pattern matching, not a C-style switch. There is no fall-through, and patterns can also match the shape of lists, tuples and dicts (for example case (x, y):). A dotted name like case Color.RED: is compared as a value; a bare name like case red: is always a capture.

Done here? The practice set for Part 3 โ€” 7 exercises with solutions โ€” is on the part page.

Search the guide