Control FlowIntermediate8 min31 / 63

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

Visual walkthrough1 / 6
1

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.

match requires Python 3.10 or newer — run `python --version` to check.
Note

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.

match checks day against each case in order and runs the first match.
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

Think of it like

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.

Matching integers works just like matching strings.
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".

Use | to group values that share the same outcome.
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:

The if/elif version works, but notice how repetitive day == is.
# 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.")
The match version removes repetition and reads almost like plain English.
# 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.

match can destructure a tuple — x and y capture the actual values.
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.

Common mistake

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.

Tip

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.

Quick check

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.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
status_code = 500

match status_code:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Server Error")
    case _:
        print("Unknown")
Fix the bug#2

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?

fix-bug
day = "Saturday"

match day:
    case "Monday" | "Friday":
        print("Weekday fun!")
    case _:
        print("Just another day.")
    case "Saturday" | "Sunday":
        print("Have a great weekend!")
Fill in the blank#3

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")
Reorder the lines#4

Put these lines in the right order so the code prints the correct grade message for a "C".

1
    case _:
2
    case "B" | "C":
3
match grade:
4
        print("Good work!")
5
        print("Keep trying!")
6
    case "A":
7
grade = "C"
8
        print("Excellent!")
Your turn
Practice exercise

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:

solution.py · editable