Python Interactive Guide - Step 2 Control Flow (6) - Pattern Matching (match statement)
- This course, Python Interactive Guide, is designed to help you learn the basics of Python programming through hands-on, interactive examples.
- The “Style Guide” sections introduce clean coding practices, mainly based on PEP8.
- You can run and experiment with every code example.
Feel free to try things out - reloading the page will reset everything.
This is a continuation of “Step 2 Control Flow.”
2.3. Pattern Matching (match
statement)
Pattern Matching is a feature introduced in Python 3.10 that allows for conditional branching based on value patterns.
2.3.1. Basic match
statement
The match
statement compares the value of an expression against multiple patterns and executes the block that matches.
- The expression (
status_code
) specified inmatch
is compared with eachcase
pattern in order - Only the block of the first matching
case
is executed case _:
is the default case that always matches and is executed when no other patterns match
2.3.2. Types of Patterns
You can use various types of patterns in a match
statement.
Basic Patterns
Literal Patterns
Checks for an exact match with constant values.
Capture Patterns
When you use a variable in a pattern, the matched value is assigned to that variable.
(This variable is only available within the case block.)
Wildcard Patterns
As seen in capture patterns, variables match any pattern.
If you don’t need to use the value, you can use an underscore (_
) as the variable name.
Structural Patterns
Sequence Patterns
Sequence patterns allow pattern matching against ordered collections like lists and tuples, matching elements as patterns.
Mapping Patterns
Similar to sequence patterns, pattern matching can be used with dictionaries:
Class Patterns
Besides lists and dictionaries, pattern matching can be performed on any class.
Since classes haven’t been covered in this course yet, here’s a brief explanation.
A class is a data structure that bundles data and its behaviors together.
For example, a class for a 2D point can be defined as follows:
Pattern matching with the above class can be written as follows:
Decorated Patterns
OR Patterns
You can use |
(pipe) to specify multiple patterns at once.
This allows you to handle similar cases together.
AS Patterns
When you want to assign the entire pattern to a single variable, you can use the as
pattern.
You can also use AS patterns in combination with OR patterns:
Guard Patterns
You can specify additional conditions using if
.
The if <condition>
part used in a match
statement is called a guard.
As seen in “Capture Patterns”, when you specify a variable name in a case
statement of a match
, the matched value is assigned to that variable.
For example, the following code might appear to be comparing against a constant (NOT_FOUND
), but
it’s actually creating a new variable NOT_FOUND
within the match
statement and assigning it a value:
To achieve the intended behavior, use a guard (if
) to compare values:
2.3.3. Pattern Matching Summary
The match
statement, introduced in Python 3.10, is a powerful feature for conditional branching based on value patterns.
Key features of the match statement:
- Compares the value of an expression against multiple patterns and executes the matching block
- Patterns are evaluated in order, and only the first matching pattern’s block is executed
- Flexible pattern descriptions allow complex conditional branching to be expressed simply
- More intuitive than if-elif-else conditionals for processing data structures
Types of Patterns:
Category | Pattern | Description | Example |
---|---|---|---|
Basic Patterns | Literal Pattern | Exact match with constant values | case 200: |
Capture Pattern | Assigns matched values to variables | case value: |
|
Wildcard Pattern | Matches any value (_ ) |
case _: |
|
Structural Patterns | Sequence Pattern | Matching list or tuple structure | case [x, y]: |
Mapping Pattern | Matching dictionary structure | case {"name": name}: |
|
Class Pattern | Matching object attributes | case Point(x=0, y=y): |
|
Decorated Patterns | OR Pattern | Multiple pattern selection | case "A" | "B": |
AS Pattern | Assigns whole match target to a variable | case (x, y) as point: |
|
Guard Pattern | Specifies additional conditions | case x if x > 0: |
Let’s create a game system that processes commands based on player input.
For this exercise, we’ll create a program that outputs specific messages for each command.
Commands are given in the following formats:
- Move command:
["move", <direction>, <steps>]
(e.g.,["move", "north", 5]
)- => “Moving
<steps>
steps<direction>
”
- => “Moving
- Attack command:
["attack", <weapon>]
(e.g.,["attack", "sword"]
)- => “Attacking with
<weapon>
”
- => “Attacking with
- Item use:
["use", <item>]
(e.g.,["use", "potion"]
)- => “Using
<item>
”
- => “Using
- Show help:
["help"]
- => “Displaying help menu”
- Exit game:
["quit"]
or["exit"]
- => “Exiting the game”
- Other commands
- => “Invalid command”
Let’s write code using a match
statement to display the appropriate message for each command.
Example solution
Let’s create a system that displays appropriate clothing advice based on weather data (a tuple of weather condition and temperature).
"rain"
and under10
°C => “It’s raining. Wear a raincoat.”"rain"
and10
°C or higher => “It’s raining. Don’t forget to bring an umbrella.”"snow"
=> “It’s snowing. Wear a heavy coat and gloves.”"sunny"
or"cloudy"
and30
°C or higher => “It’s<weather>
and hot (<temperature>°C
). Wear short sleeves.”"sunny"
and under15
°C => “It’s sunny but cool (<temperature>°C
). Bring a jacket.”"cloudy"
and under15
°C => “It’s cloudy and chilly (<temperature>°C
). Wear a jacket.”- Other cases => “It’s
<weather>
and<temperature>
°C. Dress appropriately for the season.”
Example solution
Let’s calculate the total amount for a shopping cart using pattern matching.
Each item in the cart is a tuple in the format of (product_name, quantity)
or (product_name, quantity, discount_rate)
.