match Statements
Learn how Python's match statement lets you compare a value against multiple patterns cleanly and expressively.
Imagine you work at a coffee shop and someone orders a drink. You look at the order slip and route it to the right station: espresso goes here, tea goes there, smoothie goes somewhere else. You're matching the order to an action.
Python's match statement does exactly that — it looks at a value and finds the pattern that fits, then runs the code for that pattern. It's a cleaner, more readable alternative to writing a long chain of if/elif/else checks.
See it in action
— step through the idea, then dive into the details below.Route Values Like a Pro
Python's match statement looks at a value and runs the code for the pattern that fits — like a coffee shop routing each order to the right station. It's a cleaner alternative to long if/elif chains.
Python 3.10+ required
match was introduced in Python 3.10. If you're on an older version, you'll get a SyntaxError. Run python --version to check. Most modern systems have 3.10 or later.
#Your first match statement
The basic structure looks like this: you write match followed by the value you want to examine, then a series of case branches — one for each pattern you want to handle.
day = "Monday"
match day:
case "Monday":
print("Start of the work week!")
case "Friday":
print("Almost the weekend!")
case "Saturday" | "Sunday":
print("It's the weekend!")
case _:
print("Just another weekday.")Notice a few things: - Each case is followed by a pattern (like "Monday") and a colon. - Python checks patterns top to bottom and stops at the first match. - The _ at the end is the wildcard — it matches anything that didn't match above. Think of it as the else of a match statement.
#The wildcard: _ as a catch-all
The _ is your safety net
Think of case _: like the last line in a restaurant menu that says "Chef's Choice" — it's what you get when nothing else on the menu matched your request. It guarantees the code always has something to do.
status_code = 404
match status_code:
case 200:
print("OK — everything is fine.")
case 404:
print("Not Found — the page doesn't exist.")
case 500:
print("Server Error — something broke.")
case _:
print(f"Unknown status: {status_code}")#Matching multiple values with |
Sometimes several different values should trigger the same action. You can combine them in one case using the pipe | symbol, which means "or".
grade = "B"
match grade:
case "A":
print("Excellent!")
case "B" | "C":
print("Good work, keep it up!")
case "D" | "F":
print("Let's study together and try again.")
case _:
print("I don't recognise that grade.")#Comparing match to if/elif
You can do everything match does with if/elif/else. So why use match? Because when you have many possible values, match is easier to read and harder to get wrong. Here's the same logic side by side:
# Using if/elif — gets long and repetitive
day = "Saturday"
if day == "Monday":
print("Start of the work week!")
elif day == "Friday":
print("Almost the weekend!")
elif day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("Just another weekday.")# Using match — cleaner and more expressive
day = "Saturday"
match day:
case "Monday":
print("Start of the work week!")
case "Friday":
print("Almost the weekend!")
case "Saturday" | "Sunday":
print("It's the weekend!")
case _:
print("Just another weekday.")#Matching tuples and simple structures
match gets really powerful when your value has structure — like a tuple (a pair of values). You can match on the shape and the contents at the same time.
point = (0, 5)
match point:
case (0, 0):
print("Origin — the center point.")
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"Somewhere at ({x}, {y}).")In that example, (0, y) is a pattern that means: "a tuple whose first item is 0, and whose second item I'll call y". Python fills in y automatically. This is called destructuring and it's one of the most elegant parts of match.
Variables in patterns capture, they don't compare
When you write case x: (a plain name with no quotes), Python captures the value into x — it does NOT check if the value equals some existing variable named x. Only literals (strings in quotes, numbers) and the wildcard _ are used for comparison.
``python x = 10 match 5: case x: # This always matches! It captures 5 into x, overwriting it. print(x) # prints 5, not 10 ``
If you want to compare against an existing variable, use an if guard or a different approach.
No break needed
Unlike switch in some other languages (like JavaScript or C), Python's match does not fall through from one case to the next. Once a case matches and its code runs, match is done. You never need a break statement.
What does the _ pattern in a case branch mean?
Key takeaways
- `match` compares a value against a list of `case` patterns and runs the first match — cleaner than long if/elif chains.
- The `_` wildcard acts as the default catch-all case and should come last.
- Use `|` inside a `case` to match multiple values with the same action.
- `match` can destructure tuples and sequences, capturing parts of the value into variables.
- `match` requires Python 3.10 or newer — check your version before using it.
What does this code print?
status_code = 500
match status_code:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Server Error")
case _:
print("Unknown")This code is supposed to print "Have a great weekend!" when the day is "Saturday", but it prints "Just another day." instead. What is wrong?
day = "Saturday"
match day:
case "Monday" | "Friday":
print("Weekday fun!")
case _:
print("Just another day.")
case "Saturday" | "Sunday":
print("Have a great weekend!")Complete the match statement so it prints "Freezing!" when temp is 0, and "Unknown" for any other value.
temp = 0 match temp: case : print("Freezing!") case : print("Unknown")
Put these lines in the right order so the code prints the correct grade message for a "C".
case _:
case "B" | "C":
match grade:
print("Good work!") print("Keep trying!")case "A":
grade = "C"
print("Excellent!")Write a function called describe_season(month) that accepts a month number (1–12) and uses a match statement to return a string describing the season. Use these groupings: - December, January, February → "Winter" - March, April, May → "Spring" - June, July, August → "Summer" - September, October, November → "Autumn" - Any other number → "Unknown month"
Test it by printing the result for months 3, 7, 11, and 99.
Try it live — edit the code and hit Run to execute real Python: