Contents

Python Interactive Guide - Step 2 Control Flow (6) - Pattern Matching (match statement)

Info
  • 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.”

Pattern Matching is a feature introduced in Python 3.10 that allows for conditional branching based on value patterns.

The match statement compares the value of an expression against multiple patterns and executes the block that matches.

match-case statement
match expression: case pattern1: block1 case pattern2: block2 case _: # Wildcard pattern (default case that always matches) default block
  • The expression (status_code) specified in match is compared with each case 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

You can use various types of patterns in a match statement.

Checks for an exact match with constant values.

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.)

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.

Sequence patterns allow pattern matching against ordered collections like lists and tuples, matching elements as patterns.

Similar to sequence patterns, pattern matching can be used with dictionaries:

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.

What is a Class (Simplified)

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:

You can use | (pipe) to specify multiple patterns at once.
This allows you to handle similar cases together.

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:

You can specify additional conditions using if.
The if <condition> part used in a match statement is called a guard.

Caution when using variable values in pattern matching

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:

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:
📚Exercise 1: Simple Game Command Processing

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>
  • Attack command: ["attack", <weapon>] (e.g., ["attack", "sword"])
    • => “Attacking with <weapon>
  • Item use: ["use", <item>] (e.g., ["use", "potion"])
    • => “Using <item>
  • 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
📚Exercise 2: Weather Forecast System

Let’s create a system that displays appropriate clothing advice based on weather data (a tuple of weather condition and temperature).

  • "rain" and under 10°C => “It’s raining. Wear a raincoat.”
  • "rain" and 10°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" and 30°C or higher => “It’s <weather> and hot (<temperature>°C). Wear short sleeves.”
  • "sunny" and under 15°C => “It’s sunny but cool (<temperature>°C). Bring a jacket.”
  • "cloudy" and under 15°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
📚Exercise 3: Shopping Cart Processing

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).

Example solution

Related Content