Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 4 · The`match` Statement

The match Statement

On this pageBasic ExampleMatching Multiple PatternsUsing match with NumbersMini Project — Simple Menu System

The match statement, available from Python 3.10, compares a value with patterns and runs the first matching case. It can match both simple values and the structure of data. Here we begin with literal values.

It’s especially useful when you want to match patterns — like user choices, menu commands, or specific data values — without writing several if and elif statements.

Basic Example

Each case introduces a pattern. A pipe (|) combines alternatives; _ is a wildcard used here as a fallback. The input must match the spelling and capitalization shown:

Let’s start with a day of the week:

day = input("Enter a day of the week: ")

match day:
    case "Monday":
        print("Start of the work week!")
    case "Friday":
        print("Almost the weekend!")
    case "Saturday" | "Sunday":
        print("It’s the weekend, enjoy your rest!")
    case "Tuesday" | "Wednesday" | "Thursday":
        print("Midweek day — keep going!")
    case _:
        print("Unrecognized day.")
Listing 108 — Basic Example

Example Runs:

Enter a day of the week: Friday
Almost the weekend!


Enter a day of the week: Sunday
It’s the weekend, enjoy your rest!
Listing 109 — Basic Example

In this example, Python compares the input against each case in order. Once a match is found, it executes the corresponding block and skips the rest.

The underscore _ acts as a default case, similar to else, for situations where no other case applies.

Matching Multiple Patterns

Sometimes, different inputs should lead to the same result. Instead of repeating code, you can use the pipe symbol (|) to match multiple patterns at once.

Here’s an example where we group fruits into categories:

fruit = input("Enter a fruit name: ")

match fruit:
    case "Apple" | "Pear" | "Banana":
        print("Common fruit.")
    case "Mango" | "Pineapple":
        print("Tropical fruit.")
    case _:
        print("Unrecognized fruit.")
Listing 110 — Matching Multiple Patterns

Output:

Enter a fruit name: Mango
Tropical fruit.

The program checks each pattern in turn and executes the first one that matches, keeping your logic compact and clear.

Using match with Numbers

You can also use match for numeric input — such as menu selections or response codes — to make programs easier to navigate.

In the example below, the program reacts based on the number entered by the user:

choice = int(input("Enter a menu option (1–3): "))

match choice:
    case 1:
        print("You selected: Start new game")
    case 2:
        print("You selected: Load game")
    case 3:
        print("You selected: Exit")
    case _:
        print("Invalid option.")
Listing 111 — Using match with Numbers

Example Run:

Enter a menu option (1–3): 2
You selected: Load game
Listing 112 — Using match with Numbers

Mini Project — Simple Menu System

Write a program that displays a small restaurant menu and lets the user place an order.

Use a match statement to select the meal based on the user’s choice, and apply simple conditions for size, student discount, takeaway, and vegetarian preference.

Display a short summary with the total price at the end. Apply the size multiplier first, then a 10% student discount, then a €0.50 takeaway fee if applicable. Format only the final total to two decimal places. Reject an unknown meal or size; reject a nonvegetarian dish when vegetarian food is requested. strip() removes surrounding whitespace and lower() normalizes the yes/no input.

Here’s the starting structure — complete it by adding the control flow using match,if, and else statements:

# Menu data (option: name, base price, vegetarian)
menu = {
    1: ("Pizza Margherita", 9.50, True),
    2: ("Chicken Pasta", 11.00, False),
    3: ("Veggie Salad", 7.50, True),
    4: ("Tomato Soup", 6.00, True),
}

# Size multipliers
size_factor = {"small": 0.90, "regular": 1.00, "large": 1.25}

# Display menu
print("Menu:")
print("1) Pizza Margherita  9.50")
print("2) Chicken Pasta     11.00")
print("3) Veggie Salad       7.50")
print("4) Tomato Soup        6.00")

# Collect user input
choice = int(input("Enter your choice (1–4): "))
size = ...
is_student = ...
takeaway = input("Takeaway? (yes/no): ").strip().lower() == "yes"
wants_veg = ...

# TODO: Complete the program using match, if, and else statements
# Hint: Use match to check choice, if to validate vegetarian options, and conditions to apply discounts and fees.
Listing 113 — Mini Project — Simple Menu System

Example Runs:

Example 1:

Enter your choice (1–4): 1
Size (small, regular, large): large
Student? (yes/no): yes
Takeaway? (yes/no): yes
Vegetarian preference? (yes/no): yes

--- Order Summary ---
Dish: Pizza Margherita
Size: Large
Vegetarian: Yes
Student: Yes
Takeaway: Yes
Total: €11.19


Example 2:

Enter your choice (1–4): 2
Size (small, regular, large): regular
Student? (yes/no): no
Takeaway? (yes/no): yes
Vegetarian preference? (yes/no): yes
Selected dish 'Chicken Pasta' is not vegetarian.
Suggestion: try 'Veggie Salad' or 'Tomato Soup'.
Listing 114 — Mini Project — Simple Menu System