Basic Match-Case Syntax
The match statement compares a value against multiple patterns. The first matching pattern executes its block. The case _: is the wildcard (matches anything β like "else").
Python
def describe_http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _: # wildcard - matches anything
return f"Unknown status: {status}"
print(describe_http_status(200))
print(describe_http_status(404))
print(describe_http_status(999))
βΆ Output
OK
Not Found
Unknown status: 999
OR Patterns β Multiple Values
Use | to match multiple values in a single case.
Python
def day_type(day):
match day:
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
return "Weekday"
case "Saturday" | "Sunday":
return "Weekend"
case _:
return "Invalid day"
print(day_type("Monday")) # Weekday
print(day_type("Saturday")) # Weekend
βΆ Output
Weekday
Weekend
Ad β 336Γ280
Guard Conditions with if
Add an if guard to a case for additional conditions.
Python
def classify(value):
match value:
case x if x < 0:
return f"{x} is negative"
case 0:
return "zero"
case x if x > 0 and x <= 100:
return f"{x} is between 1 and 100"
case _:
return f"{value} is over 100"
print(classify(-5))
print(classify(0))
print(classify(42))
βΆ Output
-5 is negative
zero
42 is between 1 and 100
Matching Sequences and Dicts
Match can destructure lists, tuples, and dicts directly.
Python
# Match sequences (lists/tuples)
def describe_point(point):
match point:
case [0, 0]:
return "Origin"
case [x, 0]:
return f"On X-axis at {x}"
case [0, y]:
return f"On Y-axis at {y}"
case [x, y]:
return f"Point at ({x}, {y})"
print(describe_point([0, 0]))
print(describe_point([3, 0]))
print(describe_point([4, 5]))
βΆ Output
Origin
On X-axis at 3
Point at (4, 5)