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):
Multiple Cases
You can combine multiple cases using the pipe operator | (OR), allowing a single block to handle multiple values:
Pattern Matching with Guards
You can add conditions (guards) to cases using if to create more complex matching logic:
Matching Different Types
Match statements can handle different data types and patterns. Here's an example with numbers:
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: