Chapter 22 of 54

match-case Statement in Python

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 on

It 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 match statement takes a value and compares it against a series of patterns written with case. 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 matched
  • match and every case line end with a colon :.

  • The case lines are indented inside match, and each case body is indented inside its case.

  • _ (an underscore) is the wildcard. It matches anything, so it works like else.


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:

Wednesday

How 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 checked

Three rules to remember:

  1. Cases are checked from top to bottom.

  2. Only the first matching case runs. There is no fall-through into the next case, so you never write break.

  3. 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 science

The 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: 503

Here is what happens in the third case:

  1. The pattern code is a plain name, so it matches any value and stores it in the variable code. This is called a capture pattern.

  2. Then the guard if 500 <= code <= 599 is checked.

  3. 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: 403

A 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.0

Notice 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 selected

The 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
blue

The 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 unreachable

Fixes:

  • 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

match-case

if-elif-else

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

case "Sat" | "Sun":

if day == "Sat" or day == "Sun":

Default branch

case _:

else:

Range checks

Needs a guard: case x if x > 90:

Natural: if x > 90:

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 switch

Python match

Fall-through

Yes, unless you write break (classic switch)

Never. break is not used

Default

default:

case _:

Several values

Stacked case labels

| OR pattern

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")
        break

Output:

SyntaxError: 'break' outside loop

Python 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 unreachable

Always 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 everything switch does and more. Before 3.10, people used if-elif chains 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 the match block.

  • "Why does case RED: match everything?" A bare name is a capture pattern. Only dotted names like Color.RED are treated as values to compare.

  • "Is match a reserved keyword?" No, it's a soft keyword. match and case act as keywords only in a match statement, so old code that uses match as a variable name still works.


Summary

  • match value: compares one value against case patterns, 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, if guards for extra conditions, and as to capture the matched value.

  • A bare name in a case captures the value, it does not compare it.

  • Prefer match for "which value is it?" decisions, and if-elif-else for ranges and mixed conditions.

Think of match as asking "what does this value look like?" and case as 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.