What is match case in Python?

Introduced in Python 3.10, the match case statement brings structural pattern matching to Python, similar to switch statements in other languages like C or JavaScript. It's used for cleaner and more readable multi-conditional logic.


Syntax of match case in Python:

match variable:
    case value1:
        # code block
    case value2:
        # code block
    case _:
        # default block (like else)
  • match: The keyword used to evaluate a variable.
  • case: Compares the value of the variable with specific patterns.
  • _ (underscore): Acts like else—matches anything.


Example 1: Basic match case in Python

day = "Wednesday"

match day:
    case "Monday":
        print("Start of the week")
    case "Wednesday":
        print("Midweek")
    case "Friday":
        print("Weekend is coming")
    case _:
        print("Regular day")

Output:

Midweek

Explanation:

The value "Wednesday" matches the second case, so "Midweek" is printed.



Example 2: Match Integers (like a switch case)

option = 2

match option:
    case 1:
        print("You selected Option 1")
    case 2:
        print("You selected Option 2")
    case 3:
        print("You selected Option 3")
    case _:
        print("Invalid option")

Output:

You selected Option 2


Example 3: Match with Multiple Patterns

status_code = 404

match status_code:
    case 200 | 201:
        print("Success")
    case 400 | 404:
        print("Client Error")
    case 500:
        print("Server Error")
    case _:
        print("Unknown Status")

Output:

Client Error

Explanation:

The | operator lets you match multiple values in a single case.



Example 4: Match with Tuples

user = ("admin", True)

match user:
    case ("admin", True):
        print("Welcome Admin")
    case ("guest", False):
        print("Guest access")
    case _:
        print("User not recognized")

Output:

Welcome Admin


Benefits of Using match case

  • Cleaner than long if-elif-else chains
  • More readable and organized code
  • Supports pattern matching like tuples, lists, types, and more
  • Introduced in Python 3.10 – make sure your Python version supports it


Important Notes

  • Only available in Python 3.10 and later
  • Not backward-compatible with earlier versions
  • Works best for checking discrete values, patterns, and structures