What is Match Case?
Introduced in Python 3.10, thematch statement (also called structural pattern matching) is a clean and readable alternative to writing long chains of if-elif-else statements.
Think of it like checking a variable against a list of possible matches.
Basic Syntax
Here is how you write a basicmatch statement to check response status codes:
How it works:
- Python takes the value of
status_codeand checks it against eachcase. - As soon as it finds a match, it runs the code under that case block.
- The wildcard
case _:acts as a default fallback (similar toelse). It matches anything if no previous cases matched.
Unlike some other programming languages (like Java or C++ switch statements), Python’s
match statement does not fall through. Once a match is found, only that block runs, and Python exits the match block. You don’t need break statements!Combining Patterns (| OR)
You can check if a variable matches one of multiple values in a single case block by separating them with the | (OR) symbol:
Conditional Guards (if in case)
Sometimes you want to match a pattern only if a certain condition is also met. You can add an if condition (called a guard) to a case:
n acts as a temporary variable name that captures the value of number so it can be evaluated in the if guard.
Common mistakes
Placing case _: at the beginning or middle
Placing case _: at the beginning or middle
The wildcard case
case _: matches everything. If you place it before other cases, it will always match, and the cases below it will never run! Python will raise a SyntaxError if you place it anywhere except as the last case.Using complex conditions without if guard syntax
Using complex conditions without if guard syntax
You cannot use comparison operators directly in case patterns like
case < 10:. You must use a guard pattern: case n if n < 10:.Practice & Exercises
To reinforce what you’ve learned in this section (Match Case pattern matching), practice with these interactive notebooks:Follow-Along Practice
Practice match-case basic structures, combining patterns, and using conditional guards.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your knowledge with hands-on exercises on status code matching, day patterns, and number range guards.💻 VS Code | 🚀 Colab | 📥 Download
What’s next?
Now let’s learn about loops to repeat code efficiently!Loops
Repeat code without copying