Match Case

Match Case in Python: Introduced in Python 3.10, the Match Case statement (formally known as Structural Pattern Matching) is a powerful way to handle multiple…

Concept Explanation

Introduced in Python 3.10, the Match Case statement (formally known as Structural Pattern Matching) is a powerful way to handle multiple branching conditions. While it looks similar to the "Switch" statement found in languages like C++ or Java, it is much more advanced.

Instead of writing a long chain of if...elif...elif...else statements, you can "match" a variable against a pattern. It makes your code cleaner, more readable, and less prone to errors when dealing with many possible state values (like HTTP status codes or user commands).


Syntax or Core Structure

The match and case logic

  1. The Subject: The variable you are checking (e.g., status).
  2. The Cases: Specific values or patterns you are looking for.
  3. The Wildcard (_): A special case that catches anything else that wasn't matched above (similar to else).
command = "save"

match command:
    case "open":
        print("Opening file...")
    case "save":
        print("Saving progress...")
    case "quit":
        print("Exiting...")
    case _:
        print("Unknown command.")

Code Example #1 (Basic)

Handling different user types in a system.

user_role = "editor"

match user_role:
    case "admin":
        print("Full access granted.")
    case "editor":
        print("Access to edit articles granted.")
    case "viewer":
        print("Read-only access.")
    case _:
        print("Guest access.")

Code Example #2 (Intermediate)

You can use the pipe symbol (|) to match against multiple values in a single case.

day = "Saturday"

match day:
    case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
        print("It's a weekday. Go to work!")
    case "Saturday" | "Sunday":
        print("It's the weekend! Relax.")
    case _:
        print("That's not a real day.")

Real World Example

Imagine handling specific responses from a web server API.

# 🌐 API Response Handler
response_code = 404

match response_code:
    case 200:
        print("Success: Everything is fine.")
    case 201:
        print("Success: New resource created.")
    case 400:
        print("Error: Bad request from client.")
    case 401 | 403:
        print("Error: Permission denied / Unauthorized.")
    case 404:
        print("Error: Resource not found.")
    case 500:
        print("Error: The server crashed.")
    case _:
        print("Error: An unexpected error occurred.")

Common Mistakes

  1. Wrong Python Version: match case was added in Python 3.10. If you are using an older version (like 3.8 or 3.9), this code will cause a SyntaxError.
  2. Missing the Case _: Always include the "default" case (case _:) at the end. If you don't and none of your cases match, Python won't do anything, which might lead to confusing bugs later.
  3. Indentation: Just like with if statements, the code inside each case must be indented consistently.

Best Practices

  • Use for Clarity: If you only have 2 or 3 simple checks, a standard if/else is fine. But if you have 5+ possible values, match case is significantly easier to read.
  • Pattern Matching: Remember that match can also destructure complex data like lists or dictionaries (though we'll learn about that in advanced modules!).

Practice Exercises

  1. The Season Finder: Create a variable called month. Use a match case statement to print which season it belongs to (e.g., "December", "January", "February" -> "Winter").
  2. Grade Calculator: Match a letter grade (A, B, C, D, F). Print a specific encouraging message for each grade. Use a wildcard for invalid grades.
  3. The Multi-Match: Create a script for a video game where a player types a move: "UP", "DOWN", "LEFT", "RIGHT", or "JUMP". Match the input and print the corresponding action. Allow "W", "A", "S", "D" as shortcuts using the OR (|) operator.