Python match Keyword
Example
Basic match
comparing a value against patterns:
role = "editor"
match role:
case "admin":
print("Full access")
case "editor":
print("Edit content")
case "viewer":
print("Read-only")
Try it Yourself »
Definition and Usage
The match
keyword starts a structural pattern matching statement, introduced in Python 3.10.
It compares a subject value against one or more case
patterns and executes the first matching case's block.
You can use:
- Literal patterns (numbers, strings)
- OR-patterns with
|
- Wildcard
_
to match anything (default case) - Guards with
if
for extra conditions - Sequence, mapping, and class patterns (advanced)
More Examples
Example
Group multiple values into one case using |
:
status = 404
match status:
case 400 | 404:
print("Client Error")
case 200:
print("OK")
case 500:
print("Server Error")
Try it Yourself »
Example
Use a default case with _
to catch everything else:
status = 201
match status:
case 200:
print("OK")
case 201:
print("Created")
case _:
print("Other")
Try it Yourself »
Example
Match multiple string values and use a default case:
cmd = "quit"
match cmd:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case _:
print("Unknown command")
Try it Yourself »
Example
Use |
(OR) and a guard to refine the match:
n = 10
match n:
case 0 | 1:
print("Small")
case x if x % 2 == 0:
print("Even number:", x)
case _:
print("Odd number:", n)
Try it Yourself »
Related Pages
The case
keyword.
Read more about pattern matching in our Python match Tutorial.