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: Structural Pattern Matching (the
match
statement) is available from Python 3.10 and later.
[Image comparing Python match case versus if elif else structure]
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
Only the matching block runs. No further cases are evaluated once a match is found.
Default Case Using _
The underscore (_) works like the
else clause
in an
if-else
block.
Example: Invalid Input Handler
Important: Always place
_ at the very
end, or it will intercept and override any cases placed below it.
Matching Multiple Values in One Case
You can combine multiple values into a single case block using the pipe
(|) operator.
Example: Traffic Signal Status
This acts like a logical
OR condition
grouped perfectly inside a single case.
Using Conditions with Case Guards (if)
You can attach an
if condition
directly to a case to perform additional logic checks. This is known as a
guard.
Example: Discount Rules
- ✔ Case matches the base value first
- ✔ Guard checks the extra condition before granting access to the block
Practical Example: HTTP Status Codes
This approach is significantly cleaner and much more maintainable than
writing out multiple long
elif blocks.
When to Use match
Use the match statement when:
- Comparing one specific value against many exact options
- Logic is branch-heavy or behaves like a "switch" statement
- Readability is a top priority
- You are working with Python 3.10 or newer
Avoid match for:
- Simple binary True/False decisions
-
Complex, multi-variable boolean expressions (use standard
if-elseinstead)
