← Back to Chapters

Python Match Statement

? Python Match Statement

⚡ Quick Overview

The match statement was introduced in Python 3.10 and works similarly to switch/case in other languages. It lets you compare (or match) a value against multiple patterns and run different blocks of code depending on which pattern fits.

? Key Concepts

  • match starts the pattern matching block for a value.
  • case defines individual patterns to test against that value.
  • Literal matching compares simple values like strings or numbers.
  • Multiple patterns can be combined in a single case using |.
  • Wildcard pattern _ acts like a “default” or “catch-all”.
  • Structural matching allows matching parts of dictionaries, tuples, or classes.

? Syntax & Theory

Basic structure of a match statement:

match value:
    case pattern_1:
        # code block
    case pattern_2:
        # code block
    case _:
        # default / catch-all block

The interpreter evaluates each case from top to bottom. The first pattern that matches runs its block, and the rest are skipped.

?️ Common Use Cases

  • Replacing long if-elif-else chains that compare the same variable.
  • Handling different categories of input (e.g., days, commands, user roles).
  • Matching structured data, such as coordinates, config dictionaries, or parsed JSON.

? Basic Match Example

Here we match a day name and print a message based on its value.

? View Basic Match Code
# Set the current day
day = "Monday"

# Use match to handle different days
match day:
    case "Monday":
        # Specific case for Monday
        print("Start of the week")
    case "Friday":
        # Specific case for Friday
        print("End of the week")
    case _:
        # All other days fall here
        print("Middle of the week")

? Match with Multiple Patterns

You can group several possible values into a single case using the | operator.

? View Multiple Patterns Code
# Assign a fruit name
fruit = "apple"

# Match multiple possible fruit values
match fruit:
    case "apple" | "banana" | "cherry":
        # Any of these values will match this case
        print("This is a fruit")
    case _:
        # Fallback for anything else
        print("Unknown item")

? Match with Dictionary Patterns

The match statement can also match structured data like dictionaries and extract values into variables.

? View Dictionary Pattern Code
# Define a point as a dictionary
point = {"x": 0, "y": 5}

# Use structural pattern matching to inspect coordinates
match point:
    case {"x": 0, "y": y_val}:
        # x is 0, so the point lies on the Y axis
        print(f"On Y axis at {y_val}")
    case {"x": x_val, "y": 0}:
        # y is 0, so the point lies on the X axis
        print(f"On X axis at {x_val}")
    case _:
        # Any other combination is somewhere else
        print("Somewhere else")

?️ Live Output & Explanation

  • For the day example, since day = "Monday", the output is: Start of the week.
  • For the fruit example, fruit = "apple" matches the first case, so it prints: This is a fruit.
  • For the point example, {"x": 0, "y": 5} matches {"x": 0, "y": y_val}, so y_val becomes 5 and it prints: On Y axis at 5.

If none of the explicit patterns match, the case _: block runs, acting like a default branch.

✅ Tips & Best Practices

  • Use match to replace long if-elif-else chains comparing the same variable.
  • Always keep a case _: at the end as a safe catch-all branch.
  • Group similar values into one case using | (e.g., weekend days or related commands).
  • Use dictionary or class patterns when dealing with structured data instead of manual key checks.
  • Remember: match works only in Python 3.10+. Older versions will raise a SyntaxError.
  • Don’t forget to prefix each pattern with the case keyword.

? Try It Yourself

  • Write a match statement for a variable day that prints whether it is a weekday or weekend. Group Saturday and Sunday using |.
  • Create a program that uses match to categorize an item as "fruit", "vegetable", or "unknown".
  • Define a dictionary point = {"x": 3, "y": 0} and use match to:
    • Print if the point lies on the X-axis,
    • Print if it lies on the Y-axis,
    • Or print that it is somewhere else.