Python Match Case Statement

In the last lesson, we learned about Python Nested Conditions. Now let’s look at a cleaner way to match one value against several possibilities.

A Cleaner Way to Check Many Things

We know about if, elif, and else. They are great for making decisions.

But sometimes, we have to check one value against many possibilities. And writing elif again and again gets boring.

Let me show what I mean.

day = 3
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")
elif day == 5:
print("Friday")
elif day == 6:
print("Saturday")
elif day == 7:
print("Sunday")
else:
print("Invalid day")

That works. But look at all those elif lines. So repetitive.

Python has a better way. It is called the match case statement.

What Is match case in Python?

match case is a way to check one value against many patterns.

Instead of writing if x == 1, elif x == 2, elif x == 3, we write a clean list of cases.

It is like a switch. We give it a value. It looks at each case. When it finds a match, it runs that code.

Think of it like a vending machine. We press a button. The machine matches our button to a snack. Then it gives us that snack.

That is match case.

When Was match case Added to Python?

match case was added in Python 3.10. It was released in October 2021.

So if we have Python 3.10 or newer, we can use it. If we have an older version, it will not work.

We can check our version:

import sys
print(sys.version)

If we see 3.10 or higher, we are good.

The Structure of match case in Python

match value:
case pattern1:
# do something
case pattern2:
# do something
case _:
# do something else
  • match starts the statement. We give it a value.
  • case is each possibility. We give it a pattern.
  • _ is the wildcard. It matches anything. Like else.

Each case has a colon and indented code. Just like if.

A Simple Python match case Example

Let’s rewrite the day example using match case.

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

Look how clean that is. No repeated day ==. Just case 1, case 2, case 3.

Much easier to read.

The Underscore _ in Python match case

The _ at the end is the wildcard. It matches anything.

It is like the else in an if-elif-else chain. It catches everything that did not match.

command = "hello"
match command:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case _:
print("Unknown command")

Output

Unknown command

Because “hello” did not match “start” or “stop”. So it went to the wildcard.

Matching Strings with Python match case

We can match strings too.

color = "red"
match color:
case "red":
print("Stop")
case "yellow":
print("Wait")
case "green":
print("Go")
case _:
print("Unknown color")

Output

Stop

Matching Multiple Values in One Case

We can use the pipe | to match multiple values in one case.

day = 6
match day:
case 1 | 2 | 3 | 4 | 5:
print("Weekday")
case 6 | 7:
print("Weekend")
case _:
print("Invalid day")

Output

Weekend

See the |? It means “or”. So case 1 | 2 | 3 | 4 | 5 means “1 or 2 or 3 or 4 or 5”.

That is very handy.

Matching with Conditions in Python match case

We can add a condition to a case using if. This is called a guard.

number = 15
match number:
case n if n < 0:
print("Negative")
case 0:
print("Zero")
case n if n > 0:
print("Positive")

Output

Positive

Wait. Let me explain.

The first case is n if n < 0. This means: match any value, call it n, but only if n < 0.

The second case is 0. Match exactly zero.

The third case is n if n > 0. Match any value, call it n, but only if n > 0.

Since 15 is greater than 0, it matches the third case.

The n is a variable. It captures the value. We can use it inside the case.

That is a guard. It adds a condition to a case.

Matching Lists with Python match case

We can match lists too. And we can capture parts of them.

point = [3, 5]
match point:
case [0, 0]:
print("Origin")
case [x, 0]:
print(f"On X axis at {x}")
case [0, y]:
print(f"On Y axis at {y}")
case [x, y]:
print(f"At ({x}, {y})")

Output

At (3, 5)

This is a bit advanced. But it shows what is possible.

  • case [0, 0] matches a list with exactly 0 and 0.
  • case [x, 0] matches a list with any value and 0. It captures the first value in x.
  • case [0, y] matches a list with 0 and any value. It captures the second in y.
  • case [x, y] matches a list with any two values. It captures both.

This is called pattern matching. It is powerful. But we do not need to master it right away.

Matching Dictionaries with Python match case

We can match dictionaries too.

person = {"name": "Alex", "age": 25}
match person:
case {"name": name, "age": age}:
print(f"{name} is {age} years old")

Output

Alex is 25 years old

It captures the values for the keys “name” and “age”.

Again, this is advanced. Good to know it exists. But not needed for beginners.

Python match case: A Real-Life Example — Simple Calculator

Let’s build a calculator using match case.

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")
match operation:
case "+":
print(f"Result: {num1 + num2}")
case "-":
print(f"Result: {num1 - num2}")
case "*":
print(f"Result: {num1 * num2}")
case "/":
if num2 == 0:
print("Cannot divide by zero")
else:
print(f"Result: {num1 / num2}")
case _:
print("Invalid operation")

That is clean. Compare it to the if-elif-else version. This one is much easier to read.

When to Use match case vs if-elif in Python

Use match case when:

  • We are checking one value against many possibilities
  • The possibilities are exact values (like numbers, strings)
  • We want cleaner, more readable code

Use if-elif-else when:

  • We have range conditions (age >= 18)
  • We have complex conditions with and, or, not
  • We need to support older Python versions

Both work. Let’s pick the one that makes our code clearer.

Common Mistakes with Python match case

Mistake 1: Using an Old Python Version

If we are on Python 3.9 or older, match case will not work. We will get a syntax error.

Let’s check our version. Upgrade if needed.

Mistake 2: Forgetting the Wildcard

match day:
case 1:
print("Monday")
case 2:
print("Tuesday")

If day is 5, nothing happens. Because no case matches. And there is no wildcard.

So what do we do? We add a wildcard case.

case _:
print("Unknown day")

Mistake 3: Forgetting the Colon

match day:
case 1
print("Monday")

Error! Missing colon after case 1.

So what do we do? We add the colon.

case 1:

Mistake 4: Wrong Indentation

match day:
case 1:
print("Monday")

Error! The case must be indented under match. And the print must be indented under case.

So what do we do? We indent properly.

match day:
case 1:
print("Monday")

Mistake 5: Using = Instead of _ for Wildcard

case =:
print("Unknown")

Error! The wildcard is _, not =.

So what do we do? We use _.

case _:
print("Unknown")

A Complete Python match case Example

Let’s build a simple menu system.

print("1. Say Hello")
print("2. Say Goodbye")
print("3. Exit")
choice = input("Enter your choice: ")
match choice:
case "1":
print("Hello!")
case "2":
print("Goodbye!")
case "3":
print("Exiting...")
case _:
print("Invalid choice")

Simple. Clean. Easy to add more options later.

Next, we will learn about the Python Ternary Operator and write a simple two-choice expression on one line.