Learn Python
>>> control_flow.match_case

The match-case Statement in Python

#concept

Added in Python 3.10, match-case (structural pattern matching) offers a cleaner alternative to a long if-elif chain when comparing one value against several possible patterns. It matches the value against each case in order and runs the first one that fits, with an underscore (_) acting as a catch-all default.

#how it works
1

match value:

Opens the statement, evaluating value exactly once.

2

case pattern:

Checks whether value fits that pattern.

3

Patterns can combine options

Literal values, several options joined with |, or more complex structural shapes.

4

Cases are checked top to bottom

Python runs the first match, exactly like elif.

5

case _: is the wildcard

Matches anything not caught by an earlier, more specific case.

#example
status_code = 404
 
match status_code:
case 200:
print("OK")
case 404:
print("Not Found")
case 500 | 503:
print("Server Error")
case _:
print("Unknown status")
Output
Not Found
1match status_code: evaluates status_code once (404) and compares it against each case in order.
2case 200: doesn't match.
3case 404: matches exactly, so "Not Found" prints, and Python stops checking further cases.
4case 500 | 503: shows how one case can match multiple values with |, though it’s not reached here since 404 already matched.
#use cases
Handling HTTP status codes, command names, or any small fixed set of known values
Parsing structured data like tuples or dictionaries by shape, which match-case supports beyond simple values
Replacing a long if-elif chain that compares the same variable against many literal values
Building simple command interpreters that branch on a user's typed command

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.