Python match Statement

Python match Statement

Kishore V


Python match Statement

The match statement in Python is a pattern-based control structure used to execute different blocks of code depending on the value of an expression.

It provides a cleaner and more readable alternative to long chains of if-elif-else statements, especially when you are comparing a single value against multiple possibilities.

Note: The match statement is available from Python 3.10 and later.

Why Use match Instead of if-else?

Using multiple if-elif conditions can make code lengthy and harder to maintain. The match statement:

  • Improves readability
  • Reduces repetitive comparisons
  • Clearly expresses intent
  • Is easier to extend and maintain

Basic Syntax of match

How It Works

  • The expression is evaluated once
  • Each case is checked from top to bottom
  • The first matching case is executed
  • _ acts as a default case if no match is found

Example: Menu Selection

Load Game

Only the matching block runs, and no further cases are evaluated.

Default Case Using _

The underscore (_) works like the else clause in an if-else statement.

Example: Invalid Input Handler

Unknown rating

Always place _ at the end, or it will override other cases below it.

Matching Multiple Values in One Case

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

Example: Traffic Signal Status

Prepare to stop

This acts like an OR condition inside a case.

Using Conditions with Case Guards (if)

You can attach an if condition to a case to perform additional checks. This is called a guard.

Example: Discount Rules

Student discount applied
  • Case matches the value.
  • Guard checks the extra condition.

Practical Example: HTTP Status Codes

Resource not found

This approach is clearer and more maintainable than multiple elif blocks.

When to Use match

Use the match statement when:

  • Comparing one value against many options
  • Logic is branch-heavy
  • Readability is important
  • You are working with Python 3.10+

Avoid match for:

  • Simple binary decisions
  • Complex boolean expressions (use if-else instead)

Our website uses cookies to enhance your experience. Learn More
Accept !