Python Match Case – Syntax, Examples & Uses

Introduction

Python 3.10 introduced the match-case statement, also known as Structural Pattern Matching. The match-case statement provides a cleaner and more readable way to compare a value against multiple patterns and execute the corresponding code block.

The match-case statement works similarly to the switch-case statement found in languages like Java, C#, and JavaScript, but it is much more powerful. It can match simple values, multiple values, sequences, dictionaries, and even object structures.

What is Match Case Statement?

The match-case statement is a conditional control structure introduced in Python 3.10 that allows a value to be matched against multiple patterns.

Note: Instead of writing several if-elif-else conditions, you can use a single match statement with multiple case blocks.

Example:


day = 3
match day:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case _:
        print("Invalid Day")

Output:

Wednesday

In this example:

  • match day evaluates the value of day.
  • Python checks each case.
  • When a matching case is found, the corresponding block executes.
  • The underscore (_) acts as a default case.

Syntax

The basic syntax of the match-case statement is:

match variable:


    case pattern1:
        # code block

    case pattern2:
        # code block

     case _:
        # default code block

Syntax Breakdown

  • match specifies the value to evaluate.
  • case defines a pattern to match.
  • _ acts as the default case.
  • Python executes the first matching case.

Simple Match Case Example


number = 2
match number:
    case 1:
        print("One")
    case 2:
        print("Two")
    case 3:
        print("Three")

Output:

Two

Python checks each case until it finds a match.

Match Case vs If-Elif-Else

Using If-Elif


day = 2
if day == 1:
    print("Monday")
elif day == 2:
    print("Tuesday")
elif day == 3:
    print("Wednesday")
else:
    print("Invalid")

Using Match Case


day = 2
match day:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case _:
        print("Invalid")

The match-case version is cleaner and easier to read.

Using the Default Case (_)

The underscore (_) serves as the default option.

Example:


color = "Yellow"
match color:
    case "Red":
        print("Stop")
    case "Green":
        print("Go")
    case _:
        print("Unknown Color")

Output:

Unknown Color

Matching Multiple Values

You can match multiple values using the pipe (|) operator.

Example:


day = "Saturday"
match day:
    case "Saturday" | "Sunday":
        print("Weekend")
    case _:
        print("Weekday")

Output:

Weekend

Match Case with Strings

Example:


fruit = "Apple"
match fruit:
    case "Apple":
        print("Red Fruit")
    case "Banana":
        print("Yellow Fruit")
    case "Orange":
        print("Orange Fruit")

Output:

Red Fruit

Match Case with Numbers

Example:


marks = 90
match marks:
    case 100:
        print("Perfect Score")
    case 90:
        print("Excellent")
    case 80:
        print("Very Good")

Output:

Excellent

Match Case with User Input


choice = int(input("Enter menu option: "))
match choice:
    case 1:
        print("Add Record")
    case 2:
        print("Update Record")
    case 3:
        print("Delete Record")
    case _:
        print("Invalid Option")

Output:

Enter menu option: 2
Update Record

Match Case with Lists

Python can match list patterns.


data = [1, 2]
match data:
    case [1, 2]:
        print("Matched List")
    case _:
        print("No Match")

Output:

Matched List

Match Case with Tuples

Example:


point = (0, 0)
match point:
    case (0, 0):
        print("Origin")
    case _:
        print("Other Point")

Output:

Origin

Match Case with Dictionaries

Example:


user = {"role": "admin"}
match user:
    case {"role": "admin"}:
        print("Administrator")
    case {"role": "user"}:
        print("Regular User")

Output:

Administrator

Using Guards in Match Case

A guard adds an additional condition using if.

Example:


age = 25
match age:
    case x if x >= 18:
        print("Adult")
    case _:
        print("Minor")

Output:

Adult

Real-Life Examples:

1. ATM Menu


option = 1
match option:
    case 1:
        print("Balance Inquiry")
    case 2:
        print("Cash Withdrawal")
    case 3:
        print("Deposit")
    case _:
        print("Invalid Option")

Output:

Balance Inquiry

ATM software often uses menu-based selections like this.

2. Traffic Signal System


signal = "Red"
match signal:
    case "Green":
        print("Go")
    case "Yellow":
        print("Slow Down")
    case "Red":
        print("Stop")

Output:

Stop

Traffic management systems use similar logic.

3. E-Commerce Order Status


status = "Shipped"
match status:
    case "Pending":
        print("Order Received")
    case "Shipped":
        print("Order On The Way")
    case "Delivered":
        print("Order Completed")
    case _:
        print("Unknown Status")

Output:

Order On The Way

Online shopping applications frequently use status-based workflows.

4. Student Grade Evaluation


grade = "A"
match grade:
    case "A":
        print("Excellent")
    case "B":
        print("Good")
    case "C":
        print("Average")
    case _:
        print("Needs Improvement")

Output:

Excellent

Educational software can use match-case for grading systems.

Advantages of Match Case Statement

1. Cleaner Syntax

Reduces lengthy if-elif chains.

2. Better Readability

Makes code easier to understand.

3. Powerful Pattern Matching

Supports lists, tuples, dictionaries, and objects.

4. Easier Maintenance

Adding new cases is simple.

5. Improved Organization

Groups related conditions together.

Common Mistakes

1. Using Match Case in Python Versions Below 3.10

Incorrect:


match value:
    case 1:
        print("One")

Output:

SyntaxError

This feature only works in Python 3.10 and later.

2. Forgetting the Colon

Incorrect:


match day
    case 1:
        print("Monday")

Output:

SyntaxError

Correct:


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

3. Incorrect Indentation

Incorrect:


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

Output:

SyntaxError

Always use proper indentation.

4. Forgetting the Default Case


match day:
match color:
    case "Red":
        print("Stop")

If no case matches, nothing happens.

Use:


case _:
    print("Unknown")

5. Assuming Match Case Replaces All If Statements

Match-case is excellent for pattern matching, but simple conditions may still be better handled using traditional if statements.

Conclusion

The match-case statement is a powerful feature introduced in Python 3.10 that simplifies decision-making and pattern matching. It provides a cleaner alternative to lengthy if-elif-else chains and supports advanced matching capabilities for values, sequences, dictionaries, and custom patterns. By improving readability and maintainability, match-case helps developers write more organized and efficient code.

Related Python Tutorials