Chapter 2: Control Flow / Lesson 12

Match Statements (Switch)

Introduction to Match Statements

Match statements (introduced in Python 3.10) are similar to switch statements in other languages. They provide a clean way to compare a value against multiple patterns and execute code based on which pattern matches.

Match statements are more powerful than traditional if-elif chains because they support pattern matching, making code more readable and less error-prone.

Basic Match Statement

The basic syntax matches a value against specific cases. The underscore _ acts as a default case (like else):

match.py
day = "Monday" match day: case "Monday": print("Start of week") case "Friday": print("TGIF!") case _: print("Regular day")

Multiple Cases

You can combine multiple cases using the pipe operator | (OR), allowing a single block to handle multiple values:

multiple_cases.py
day = "Saturday" match day: case "Monday" | "Tuesday" | "Wednesday" | "Thursday": print("Weekday") case "Friday": print("TGIF!") case "Saturday" | "Sunday": print("Weekend!") case _: print("Invalid day")

Pattern Matching with Guards

You can add conditions (guards) to cases using if to create more complex matching logic:

guards.py
age = 25 status = "active" match status: case "active" if age >= 18: print("Adult account") case "active": print("Minor account") case "inactive": print("Account suspended") case _: print("Unknown status")

Matching Different Types

Match statements can handle different data types and patterns. Here's an example with numbers:

types.py
value = 42 match value: case 0: print("Zero") case 1 | 2 | 3: print("Small number") case 42: print("The answer to everything!") case _ if value > 100: print("Large number") case _: print("Other number")

Match vs If-Elif

Match statements are often more readable than long if-elif chains, especially when comparing a single variable against multiple values:

💡 When to Use Match

Use match when comparing one value against multiple possibilities. It's cleaner and more Pythonic for this use case.

💡 When to Use If-Elif

Use if-elif when conditions are complex or involve multiple variables, or when you need to check different types of conditions.

Practical Example: Command Handler

Here's a practical example using match to handle different commands:

command_handler.py
command = "start" match command.lower(): case "start": print("Starting application...") case "stop": print("Stopping application...") case "pause": print("Pausing application...") case "resume": print("Resuming application...") case _: print(f"Unknown command: {command}")
🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...