Sub topic 1
Your First `match` Statement
Prerequisites
Assume Python 3.10 or later. You should know functions, return, conditionals, and basic lists, tuples, and dictionaries.
Python’s match statement compares one subject with several case patterns. Python tests cases from top to bottom and runs the first matching case. If no case matches, execution continues after the statement.
def http_status(code):
match code:
case 200:
return "OK"
case 301 | 302:
return "Redirect"
case 404:
return "Not Found"
case _:
return "Unknown"
print(http_status(302)) # Redirect
print(http_status(500)) # UnknownMatching Literal Values
A literal pattern compares the subject with a literal value such as 200, "ready", True, or None. The first example uses integer literals to classify an HTTP status code.
A case can contain several alternatives separated by |. This is an or-pattern. case 301 | 302 matches either redirect status without repeating the result.
Capturing Values and the `_` Wildcard
A bare name in a pattern captures the subject instead of comparing it. For example:
def describe(value):
match value:
case 0:
return "zero"
case number:
return f"some other value: {number}"
print(describe(7)) # some other value: 7Here, number receives the value 7. A capture pattern matches almost anything, so it usually belongs near the end. The underscore, _, is a wildcard. It matches anything but does not bind a name:
def fallback(value):
match value:
case "yes":
return True
case _:
return FalseThe wildcard is useful as a default case. It also prevents an unmatched value from producing no result when every path should be handled.
Exercise
What does case 10 | 20: match, and what does case _: do?
Show answer
The or-pattern matches either 10 or 20. The wildcard matches any remaining value without capturing it.