How to Use Match Case in Python: Simple Guide with Examples
In Python,
match and case provide a way to check a value against different patterns, similar to a switch statement. You write match followed by the variable, then use case blocks to handle different values or patterns.Syntax
The match statement starts with the keyword match followed by the variable to check. Inside, you write one or more case blocks to compare the variable against specific values or patterns. Each case block ends with a colon and contains the code to run if the pattern matches.
- match variable: Start matching on this variable.
- case pattern: Check if variable fits this pattern.
- _ (underscore): Acts as a default case if no other matches.
python
match variable:
case pattern1:
# code for pattern1
case pattern2:
# code for pattern2
case _:
# default code if no pattern matchesExample
This example shows how to use match case to print a message based on a fruit name. It demonstrates matching exact values and using the default case.
python
fruit = 'apple' match fruit: case 'apple': print('This is an apple.') case 'banana': print('This is a banana.') case _: print('Unknown fruit.')
Output
This is an apple.
Common Pitfalls
One common mistake is forgetting the colon : after case or match. Another is using case without proper indentation. Also, match case checks patterns exactly, so using variables inside case without pattern syntax won't work as expected.
Wrong example (missing colon):
python
match value
case 1
print('One')Common Pitfalls
Corrected version with colons and indentation:
python
match value:
case 1:
print('One')Key Takeaways
Use
match with case to check a variable against multiple patterns clearly.Always include a colon
: after match and each case.Use underscore
_ as a default case to catch unmatched patterns.Indent
case blocks properly inside the match statement.Match case works best for exact values or simple patterns, not complex expressions.