Python•Pattern Matching
Python match...case Statement (Structural Pattern Matching)
match...case matches subject values against patterns, extracting data and executing the first matching branch with optional wildcard fallback (_).
Syntax
match expression:
case pattern1:
# action 1
case pattern2:
# action 2
case _:
# wildcard default
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| expression | Any object | Subject value being evaluated. |
| pattern | Literal, Sequence, or Class | Target structure to match against. |
| case _ | Wildcard | Matches everything; acts as the default fallback. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Python locally:
# Python 3.10+ match...case Pattern Matching
def parse_http_code(status_code: int) -> str:
match status_code:
case 200:
return "200: OK (Request succeeded)"
case 301 | 302:
return f"{status_code}: Redirect (Resource moved)"
case 400 | 404:
return f"{status_code}: Client Error (Bad request or not found)"
case 500:
return "500: Internal Server Error"
case _:
return f"{status_code}: Unrecognized Status Code"
codes_to_test = [200, 301, 404, 503]
for code in codes_to_test:
print(parse_http_code(code))Expected Output:
200: OK (Request succeeded) 301: Redirect (Resource moved) 404: Client Error (Bad request or not found) 503: Unrecognized Status Code
How It Works: Step-by-Step
- Line 3: Begins match evaluation on the numeric status_code.
- Lines 6, 8: Uses the pipe operator | to match multiple alternative cases in one branch.
- Line 12: case _ provides the universal wildcard default.
Key Concepts
- match-case replaces long elif chains with clean declarative pattern matching.
- No break statements are required; execution halts after the first matched case.
- case _ is equivalent to the default case in C/C++/Java switch statements.
Common Mistake: Placing the wildcard case _ before other specific case statements
case _ matches everything; placing it earlier hides all subsequent cases.
❌ Incorrect
match val:
case _:
print("Default")
case 1: # Unreachable code
print("One")✅ Correct
match val:
case 1:
print("One")
case _:
print("Default")Related Python Tutorials & Compiler
Python If...Else Conditional Statements with Examples
Decision making in Python is performed using if, elif, and else statements to execute code blocks based on boolean conditions.
Python For Loops and the range() Function
A for loop in Python is used for iterating over a sequence (such as a list, tuple, string, or range).
Python Functions (def): Arguments, *args, **kwargs & Return
Functions are organized, reusable blocks of code defined using the def keyword to perform a specific action.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.