← Back to Python Course | Chapter 3: Control Flow | Lesson 4 of 10

Python match Statement

Basic Match-Case

Introduced in Python 3.10, match/case compares one value against a series of patterns and runs the block for the first match — it reads more like a lookup table than an elif ladder, especially once you're checking more than two or three cases.

Example: Basic Match-Case

python
command = "start"
match command:
    case "start":
        print("Starting")
    case "stop":
        print("Stopping")

Wildcard Fallback (case _)

The underscore _ acts as a catch-all pattern that always matches, functioning exactly like the final else in an if/elif ladder — Python's linter will also warn you if a match block is missing one and could fall through with no match.

Example: Wildcard Fallback (case _)

python
command = "pause"
match command:
    case "start":
        print("Starting")
    case _:
        print("Unknown command")

Grouping Cases with |

The | operator inside a case groups multiple values that should trigger the same block, like case "y" | "yes":, avoiding the need for separate, duplicate cases that do identical work.

Example: Grouping Cases with |

python
answer = "y"
match answer:
    case "y" | "yes":
        print("Confirmed")
    case _:
        print("Not confirmed")

Match-Case with Guards

Adding an if clause after a pattern — called a guard — lets a case match only when both the pattern *and* an extra condition hold, such as case n if n > 0:, combining structural matching with an ordinary boolean check.

Example: Match-Case with Guards

python
n = 5
match n:
    case n if n > 0:
        print("Positive")
    case _:
        print("Not positive")

Matching Sequences

Beyond simple value matching, match can destructure sequences directly in the pattern — case [x, y]: binds x and y to a two-element list's contents in one line, something an elif ladder can't express nearly as cleanly.

Example: Matching Sequences

python
point = [3, 4]
match point:
    case [x, y]:
        print(x, y)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.