Imagine you're writing a program that turns a day number into a day name. With what you know so far, you would write a long if-elif-else chain that compares the same variable again and again:
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
# ... and so onIt works, but day == is repeated on every line. Since Python 3.10, there is a cleaner way to write this kind of "which one of these values is it?" decision: the match-case statement.
What is match-case?
The
matchstatement takes a value and compares it against a series of patterns written withcase. The block under the first pattern that matches is run, and the rest are skipped.
If you know C, C++ or Java, it looks like a switch statement. But Python's version is more powerful, and its official name is structural pattern matching. It was added in Python 3.10 (PEP 634), so you need Python 3.10 or newer to use it.
Basic Syntax
match value:
case pattern1:
# runs if value matches pattern1
case pattern2:
# runs if value matches pattern2
case _:
# runs if nothing above matchedmatchand everycaseline end with a colon:.The
caselines are indented insidematch, and each case body is indented inside itscase._(an underscore) is the wildcard. It matches anything, so it works likeelse.
Your First match Statement
day = 3
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
case _:
print("Invalid day")Output:
WednesdayHow Python Runs It
day = 3
case 1 -> 3 == 1 ? No, try next
case 2 -> 3 == 2 ? No, try next
case 3 -> 3 == 3 ? YES -> print("Wednesday") and leave the match
case 4 ... case _ -> never checkedThree rules to remember:
Cases are checked from top to bottom.
Only the first matching case runs. There is no fall-through into the next case, so you never write
break.If no case matches and there is no
case _, nothing happens. Python does not raise an error.
If day were 9, the wildcard case would run and print Invalid day.
Matching Strings
Cases can be strings too, which is very handy for menus and commands:
language = "python"
match language:
case "python":
print("Great for beginners and data science")
case "java":
print("Popular for Android and enterprise apps")
case "c":
print("Close to the hardware")
case _:
print("I don't know that one")Output:
Great for beginners and data scienceThe comparison is exact and case-sensitive, so "Python" would not match "python". A simple fix is to match on language.lower(), using the string method you learned earlier.
Matching Several Values with |
When different values should do the same thing, join them with | (read it as "or"). This is called an OR pattern:
day = "Sun"
match day:
case "Sat" | "Sun":
print("Weekend! Time to relax.")
case "Mon" | "Tue" | "Wed" | "Thu" | "Fri":
print("Weekday. Time to study.")
case _:
print("Not a valid day")Output:
Weekend! Time to relax.Inside a case, you must use |, not the or keyword. Writing case "Sat" or "Sun": is a SyntaxError.
Adding Conditions with Guards
Sometimes a fixed value isn't enough. You may want "any number between 500 and 599". For this, add an if after the pattern. This is called a guard:
status = 503
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case code if 500 <= code <= 599:
print("Server error:", code)
case _:
print("Some other status")Output:
Server error: 503Here is what happens in the third case:
The pattern
codeis a plain name, so it matches any value and stores it in the variablecode. This is called a capture pattern.Then the guard
if 500 <= code <= 599is checked.The case is chosen only if the guard is
True. Otherwise, Python moves on to the next case.
Capturing with as
With an OR pattern, you can also save whichever value matched using as:
status = 403
match status:
case 200 | 201 | 204 as code:
print("Success:", code)
case 400 | 401 | 403 | 404 as code:
print("Client error:", code)
case _:
print("Something else")Output:
Client error: 403A Practical Example: Simple Calculator
a = 20
b = 4
operator = "/"
match operator:
case "+":
print(a + b)
case "-":
print(a - b)
case "*":
print(a * b)
case "/" if b != 0:
print(a / b)
case "/":
print("Cannot divide by zero")
case _:
print("Unknown operator")Output:
5.0Notice the order of the two "/" cases. The first one only matches when b != 0. If b were 0, the guard would fail and Python would fall back to the second "/" case.
You can combine this with input() to build a menu:
choice = input("1. Check balance 2. Deposit 3. Exit\nEnter choice: ")
match choice:
case "1":
print("Your balance is Rs. 5000")
case "2":
print("Deposit selected")
case "3":
print("Thank you!")
case _:
print("Invalid choice")If the user enters 2:
1. Check balance 2. Deposit 3. Exit
Enter choice: 2
Deposit selectedThe cases are strings like "1" because input() always returns a string. Writing case 1: here would never match.
The Biggest Trap: Bare Names Capture, They Don't Compare
This is the mistake that surprises almost everyone. Suppose you store a value in a variable and try to use it in a case:
RED = "red"
color = "blue"
match color:
case RED:
print("It is red")
print(RED)Output:
It is red
blueThe colour was blue, yet it printed "It is red"! And RED is now "blue". Why?
In a case, a bare name like RED is a capture pattern. It does not mean "compare with the variable RED". It means "match anything and store it in RED". So the case always matches and overwrites your variable.
If you add another case after it, Python even refuses to run the code:
RED = "red"
color = "blue"
match color:
case RED:
print("It is red")
case _:
print("Some other colour")Output:
SyntaxError: name capture 'RED' makes remaining patterns unreachableFixes:
Write the literal value directly:
case "red":Use a guard:
case c if c == RED:Use a dotted name, such as a constant inside a class or module (
case Color.RED:). Names with a dot are compared, not captured. You'll be able to use this once you learn classes.
A Peek at Real Pattern Matching
So far, match has looked like a neat switch. Its real power is that a pattern can describe the shape of the data and pull values out of it at the same time. Here's a small taste using split(), which you met in the String Methods chapter:
command = "go north"
match command.split():
case ["quit"]:
print("Goodbye!")
case ["go", direction]:
print("Moving", direction)
case ["pick", "up", item]:
print("You picked up the", item)
case _:
print("I don't understand")Output:
Moving north"go north".split() gives ["go", "north"]. The pattern ["go", direction] means "a list of exactly two items whose first item is "go"". It matches, and the second item is stored in direction. Doing this with if-elif would need length checks and indexing. You'll understand these list patterns fully after the Lists chapter. Patterns can also match dictionaries and objects, which is why match is so popular for handling commands, JSON data and parsed input.
match-case vs if-elif-else
Feature |
|
|
|---|---|---|
Best for | Comparing one value against many possible values or shapes | Any conditions, including ranges and checks on different variables |
Python version | 3.10 and newer | All versions |
Several values in one branch |
|
|
Default branch |
|
|
Range checks | Needs a guard: | Natural: |
Pulling values out of data | Built in (capture patterns) | Manual indexing |
A good rule: if every branch starts with variable == something, match is usually cleaner. If your conditions are ranges like marks-to-grade, keep using if-elif-else. A match with a guard in every case is harder to read than a plain if chain.
Also, match is not faster than if-elif. Python still checks the cases one by one from the top, so it's about readability, not speed.
Python's match vs C/Java switch
Point | C / Java | Python |
|---|---|---|
Fall-through | Yes, unless you write | Never. |
Default |
|
|
Several values | Stacked |
|
What can be matched | Mainly constants (newer Java versions also support type patterns) | Constants, plus sequences, dictionaries and objects, with capturing and guards |
Common Mistakes
1. Writing break at the End of a Case
x = 1
match x:
case 1:
print("One")
breakOutput:
SyntaxError: 'break' outside loopPython never falls through to the next case, so break is not needed (and not allowed outside a loop).
2. Putting case _ Before Other Cases
The wildcard matches everything, so any case after it could never run. Python catches this:
SyntaxError: wildcard makes remaining patterns unreachableAlways keep case _: as the last case.
3. Using a Variable Name as a Constant
case RED: captures instead of comparing. Use a literal, a guard, or a dotted name, as shown above.
4. Using or Instead of |
case "y" or "yes": is a SyntaxError. Write case "y" | "yes":.
5. Matching input() Against Numbers
input() returns a string, so case 1: never matches "1". Either match strings (case "1":) or convert first with int().
6. Running on an Old Python Version
On Python 3.9 or older, match gives a SyntaxError. Check your version with python --version.
Interview Tips
"Does Python have a switch statement?" Not a classic one, but since Python 3.10 it has
match-case(structural pattern matching), which covers everythingswitchdoes and more. Before 3.10, people usedif-elifchains or dictionaries."Is there fall-through?" No. Only the first matching case runs.
"What happens if nothing matches and there is no
case _?" Nothing. No error is raised; the program continues after thematchblock."Why does
case RED:match everything?" A bare name is a capture pattern. Only dotted names likeColor.REDare treated as values to compare."Is
matcha reserved keyword?" No, it's a soft keyword.matchandcaseact as keywords only in amatchstatement, so old code that usesmatchas a variable name still works.
Summary
match value:compares one value againstcasepatterns, from top to bottom (Python 3.10+).Only the first matching case runs. There is no fall-through and no
break.case _:is the wildcard (default) and must come last.Use
|to match several values in one case,ifguards for extra conditions, andasto capture the matched value.A bare name in a case captures the value, it does not compare it.
Prefer
matchfor "which value is it?" decisions, andif-elif-elsefor ranges and mixed conditions.
Think of
matchas asking "what does this value look like?" andcaseas listing the answers you expect.
That completes decision-making in Python. In the next chapter, we'll start learning loops, which let your program repeat work automatically.