Basic Match and Case Block Syntax

🏷️ Conditional Logic and Decision Making / The Match Statement

🧠 Context Introduction

When writing scripts to handle different types of inputs, configurations, or system states, you often need to check a value against multiple possible conditions. While if-elif-else chains work, they can become messy and hard to read. Python's match-case statement (introduced in Python 3.10) provides a cleaner, more expressive way to perform pattern matching. Think of it like a switch statement found in other languages, but much more powerful. It allows you to compare a value against several patterns and execute the corresponding block of code.


βš™οΈ The Basic Structure

A match-case block starts with the match keyword followed by the value you want to inspect. Then, you define one or more case blocks, each representing a pattern to match against.

The basic syntax looks like this:

  • match followed by the variable or expression you want to evaluate.
  • case followed by the pattern you want to compare.
  • A colon : after the pattern.
  • The code to execute if the pattern matches, indented under the case.

A simple example:

  • match status_code:
  • case 200: print("Success")
  • case 404: print("Not Found")
  • case 500: print("Server Error")

If status_code is 200, the script prints "Success". If it's 404, it prints "Not Found", and so on.


πŸ› οΈ The Default Case: Underscore

What happens if the value doesn't match any of the specified patterns? You use the underscore (_) as a wildcard or default case. It acts like the else in an if-else chain.

Example:

  • match response_code:
  • case 200: print("OK")
  • case 301: print("Moved Permanently")
  • case _: print("Unknown response")

If response_code is 200 or 301, the specific message prints. For any other value, the script prints "Unknown response".


πŸ•΅οΈ Matching Multiple Values in One Case

You can match multiple values in a single case by using the pipe symbol | (which means "or"). This is useful when different inputs should trigger the same action.

Example:

  • match error_type:
  • case 400 | 401 | 403: print("Client error")
  • case 500 | 502 | 503: print("Server error")
  • case _: print("Other error")

If error_type is 400, 401, or 403, it prints "Client error". If it's 500, 502, or 503, it prints "Server error".


πŸ“Š Match-Case vs. If-Elif-Else

Here is a quick comparison to show when each approach might be better:

Feature Match-Case If-Elif-Else
Readability Cleaner for many fixed value checks Can become cluttered with many conditions
Pattern Matching Supports complex patterns (lists, dicts, etc.) Limited to boolean expressions
Default Case Uses underscore _ Uses else
Multiple Values Uses pipe ** ** for OR logic
Best Use Case Checking a single variable against many known values Complex logical conditions or range checks

πŸ§ͺ Practical Example: Handling User Input

Imagine you are writing a small script that asks a user for a command. Using match-case makes the logic very clear.

  • command = input("Enter command: ").lower()
  • match command:
  • case "start": print("Starting service...")
  • case "stop": print("Stopping service...")
  • case "restart": print("Restarting service...")
  • case "status": print("Checking status...")
  • case _: print("Unknown command")

If the user types "start", the script responds accordingly. Any other input falls to the default case.


🧩 Key Points to Remember

  • The match statement evaluates a single value against multiple patterns.
  • Each case defines a pattern to match.
  • The underscore (_) acts as a catch-all default.
  • Use the pipe (|) to match multiple values in one case.
  • Match-case is best for fixed, known values, not for complex conditional logic.
  • Indentation is criticalβ€”each case block must be indented consistently.

πŸš€ Next Steps

Practice by converting simple if-elif-else chains in your existing scripts to match-case blocks. Start with small examples like status codes or menu options. As you get comfortable, explore more advanced patterns like matching against lists or dictionaries. This will make your code cleaner and more maintainable.


The match-case block is Python's pattern matching feature that compares a value against multiple patterns and executes the code for the first matching pattern.

🎯 Example 1: Matching a single exact value

This example shows the simplest match-case structure that checks if a variable equals a specific number.

status_code = 200

match status_code:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Server Error")

πŸ“€ Output: OK


πŸ”€ Example 2: Using a default case with underscore

This example demonstrates how to catch any unmatched value using the underscore wildcard pattern.

color = "purple"

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

πŸ“€ Output: Unknown color


πŸ”’ Example 3: Matching multiple values in one case

This example shows how to match several possible values using the pipe operator within a single case.

day = "Saturday"

match day:
    case "Saturday" | "Sunday":
        print("Weekend")
    case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
        print("Weekday")
    case _:
        print("Invalid day")

πŸ“€ Output: Weekend


πŸ”— Example 4: Matching with variable binding

This example demonstrates how to capture the matched value into a variable for use inside the case block.

command = "move left"

match command.split():
    case ["move", direction]:
        print(f"Moving {direction}")
    case ["stop"]:
        print("Stopping")
    case _:
        print("Unknown command")

πŸ“€ Output: Moving left


πŸ› οΈ Example 5: Practical input validation

This example shows a real-world use case for validating user input with match-case.

user_input = "yes"

match user_input.lower():
    case "yes" | "y":
        print("Proceeding with operation")
    case "no" | "n":
        print("Cancelling operation")
    case "help" | "?":
        print("Available commands: yes, no, help")
    case _:
        print("Invalid input. Type 'help' for options")

πŸ“€ Output: Proceeding with operation


Comparison Table: Match-Case vs If-Elif-Else

Feature Match-Case If-Elif-Else
Pattern matching Supports patterns, sequences, and variable binding Only supports boolean expressions
Readability Cleaner for multiple exact value checks Better for complex conditions
Default case Uses underscore _ Uses else
Performance Optimized for pattern matching General purpose conditional logic

🧠 Context Introduction

When writing scripts to handle different types of inputs, configurations, or system states, you often need to check a value against multiple possible conditions. While if-elif-else chains work, they can become messy and hard to read. Python's match-case statement (introduced in Python 3.10) provides a cleaner, more expressive way to perform pattern matching. Think of it like a switch statement found in other languages, but much more powerful. It allows you to compare a value against several patterns and execute the corresponding block of code.


βš™οΈ The Basic Structure

A match-case block starts with the match keyword followed by the value you want to inspect. Then, you define one or more case blocks, each representing a pattern to match against.

The basic syntax looks like this:

  • match followed by the variable or expression you want to evaluate.
  • case followed by the pattern you want to compare.
  • A colon : after the pattern.
  • The code to execute if the pattern matches, indented under the case.

A simple example:

  • match status_code:
  • case 200: print("Success")
  • case 404: print("Not Found")
  • case 500: print("Server Error")

If status_code is 200, the script prints "Success". If it's 404, it prints "Not Found", and so on.


πŸ› οΈ The Default Case: Underscore

What happens if the value doesn't match any of the specified patterns? You use the underscore (_) as a wildcard or default case. It acts like the else in an if-else chain.

Example:

  • match response_code:
  • case 200: print("OK")
  • case 301: print("Moved Permanently")
  • case _: print("Unknown response")

If response_code is 200 or 301, the specific message prints. For any other value, the script prints "Unknown response".


πŸ•΅οΈ Matching Multiple Values in One Case

You can match multiple values in a single case by using the pipe symbol | (which means "or"). This is useful when different inputs should trigger the same action.

Example:

  • match error_type:
  • case 400 | 401 | 403: print("Client error")
  • case 500 | 502 | 503: print("Server error")
  • case _: print("Other error")

If error_type is 400, 401, or 403, it prints "Client error". If it's 500, 502, or 503, it prints "Server error".


πŸ“Š Match-Case vs. If-Elif-Else

Here is a quick comparison to show when each approach might be better:

Feature Match-Case If-Elif-Else
Readability Cleaner for many fixed value checks Can become cluttered with many conditions
Pattern Matching Supports complex patterns (lists, dicts, etc.) Limited to boolean expressions
Default Case Uses underscore _ Uses else
Multiple Values Uses pipe ** ** for OR logic
Best Use Case Checking a single variable against many known values Complex logical conditions or range checks

πŸ§ͺ Practical Example: Handling User Input

Imagine you are writing a small script that asks a user for a command. Using match-case makes the logic very clear.

  • command = input("Enter command: ").lower()
  • match command:
  • case "start": print("Starting service...")
  • case "stop": print("Stopping service...")
  • case "restart": print("Restarting service...")
  • case "status": print("Checking status...")
  • case _: print("Unknown command")

If the user types "start", the script responds accordingly. Any other input falls to the default case.


🧩 Key Points to Remember

  • The match statement evaluates a single value against multiple patterns.
  • Each case defines a pattern to match.
  • The underscore (_) acts as a catch-all default.
  • Use the pipe (|) to match multiple values in one case.
  • Match-case is best for fixed, known values, not for complex conditional logic.
  • Indentation is criticalβ€”each case block must be indented consistently.

πŸš€ Next Steps

Practice by converting simple if-elif-else chains in your existing scripts to match-case blocks. Start with small examples like status codes or menu options. As you get comfortable, explore more advanced patterns like matching against lists or dictionaries. This will make your code cleaner and more maintainable.

Interactive Views

You are currently in πŸ“š All-in-One mode. Use the tabs at the top to switch to πŸ“– Theory Only or πŸ’» Code Only views.

The match-case block is Python's pattern matching feature that compares a value against multiple patterns and executes the code for the first matching pattern.

🎯 Example 1: Matching a single exact value

This example shows the simplest match-case structure that checks if a variable equals a specific number.

status_code = 200

match status_code:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Server Error")

πŸ“€ Output: OK


πŸ”€ Example 2: Using a default case with underscore

This example demonstrates how to catch any unmatched value using the underscore wildcard pattern.

color = "purple"

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

πŸ“€ Output: Unknown color


πŸ”’ Example 3: Matching multiple values in one case

This example shows how to match several possible values using the pipe operator within a single case.

day = "Saturday"

match day:
    case "Saturday" | "Sunday":
        print("Weekend")
    case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
        print("Weekday")
    case _:
        print("Invalid day")

πŸ“€ Output: Weekend


πŸ”— Example 4: Matching with variable binding

This example demonstrates how to capture the matched value into a variable for use inside the case block.

command = "move left"

match command.split():
    case ["move", direction]:
        print(f"Moving {direction}")
    case ["stop"]:
        print("Stopping")
    case _:
        print("Unknown command")

πŸ“€ Output: Moving left


πŸ› οΈ Example 5: Practical input validation

This example shows a real-world use case for validating user input with match-case.

user_input = "yes"

match user_input.lower():
    case "yes" | "y":
        print("Proceeding with operation")
    case "no" | "n":
        print("Cancelling operation")
    case "help" | "?":
        print("Available commands: yes, no, help")
    case _:
        print("Invalid input. Type 'help' for options")

πŸ“€ Output: Proceeding with operation


Comparison Table: Match-Case vs If-Elif-Else

Feature Match-Case If-Elif-Else
Pattern matching Supports patterns, sequences, and variable binding Only supports boolean expressions
Readability Cleaner for multiple exact value checks Better for complex conditions
Default case Uses underscore _ Uses else
Performance Optimized for pattern matching General purpose conditional logic