Match & Case
Learn how to use Python's pattern matching with match and case — a cleaner way to handle multiple conditions.
Match & Case
Sometimes you have one value and you want to check it against many possible options. You could write a long chain of elif statements — but Python 3.10 introduced a cleaner way to do this: match and case.
match/case requires Python 3.10 or newer. Run python3 --version to check. If you are on an older version, use if/elif/else instead.
The problem it solves
Imagine you are building a simple menu. With elif it looks like this:
day = "Monday"
if day == "Monday":
print("Start of the work week.")
elif day == "Wednesday":
print("Midweek.")
elif day == "Friday":
print("Almost the weekend!")
elif day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("Just another day.")This works, but it is repetitive. You write day == over and over. With match/case:
day = "Monday"
match day:
case "Monday":
print("Start of the work week.")
case "Wednesday":
print("Midweek.")
case "Friday":
print("Almost the weekend!")
case "Saturday" | "Sunday":
print("It's the weekend!")
case _:
print("Just another day.")Cleaner. You say what you are matching once at the top, then list the cases below.
Basic structure
match value:
case pattern1:
code to run
case pattern2:
code to run
case _:
code to run if nothing matchedmatchtakes the value you want to check- Each
casedefines a pattern to compare against case _is the default — it matches anything that did not match above. Think of it as theelse
The underscore _ in case _ is called a wildcard. It means "anything". It is optional — if you leave it out and nothing matches, Python just moves on silently.
Matching numbers
status_code = 404
match status_code:
case 200:
print("OK — request succeeded.")
case 201:
print("Created — new resource made.")
case 400:
print("Bad request — check your input.")
case 401:
print("Unauthorized — please log in.")
case 404:
print("Not found — that page does not exist.")
case 500:
print("Server error — something went wrong on our end.")
case _:
print(f"Unknown status code: {status_code}")Output:
Not found — that page does not exist.Matching multiple values in one case
Use | (the pipe symbol) to match several values in a single case:
day = "Saturday"
match day:
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
print("Weekday.")
case "Saturday" | "Sunday":
print("Weekend!")
case _:
print("That is not a valid day.")Output:
Weekend!Matching with a condition — guards
You can add an if condition to a case. This is called a guard. The case only matches if both the pattern matches and the guard is true.
age = 17
match age:
case n if n < 0:
print("That is not a valid age.")
case n if n < 18:
print(f"You are {n}. You are a minor.")
case n if n < 65:
print(f"You are {n}. You are an adult.")
case n:
print(f"You are {n}. Senior citizen.")Output:
You are 17. You are a minor.Here n is a capture variable — it captures the value being matched so you can use it inside the case block.
Matching tuples
match becomes especially powerful when you match against structured data like tuples. Each position in the tuple can be matched separately.
point = (0, 5)
match point:
case (0, 0):
print("Origin.")
case (x, 0):
print(f"On the x-axis at {x}.")
case (0, y):
print(f"On the y-axis at {y}.")
case (x, y):
print(f"Point at x={x}, y={y}.")Output:
On the y-axis at 5.Python matched the pattern (0, y) — the first value was 0 and the second was captured as y.
match vs if/elif — when to use which
| Situation | Use |
|---|---|
| Checking one value against many exact options | match/case |
Complex conditions with and, or, comparisons | if/elif/else |
| Matching structured data like tuples | match/case |
| Python version older than 3.10 | if/elif/else |
| Simple true/false check | if/elif/else |
match/case is not a replacement for if/elif — it is a tool for a specific job. When you are comparing one value against a list of known possibilities, match is cleaner. When your logic is more complex, stick with if/elif.
A real example
A simple command-line tool that responds to user commands:
command = input("Enter a command (start / stop / restart / status): ").lower()
match command:
case "start":
print("Starting the server...")
case "stop":
print("Stopping the server...")
case "restart":
print("Restarting the server...")
case "status":
print("Server is running.")
case _:
print(f"Unknown command: '{command}'. Try start, stop, restart, or status.")Output:
Enter a command: restart
Restarting the server...Summary
| Concept | Example |
|---|---|
| Basic match | match value: / case "option": |
| Wildcard default | case _: |
| Multiple values | case "a" | "b": |
| Guard condition | case n if n > 0: |
| Capture variable | case n: — captures the value |
| Tuple matching | case (x, 0): |