Guards and Wildcards
Add conditions and catch-all cases.
Refining Matches
Sometimes a structural pattern is not enough; you also need a condition. Guards add an if test to a case, and wildcards give you flexible catch-alls.
Adding a Guard
Write if <condition> after a pattern. The case matches only when the pattern fits and the guard is true.
n = 7
match n:
case x if x < 0:
print('negative')
case x if x == 0:
print('zero')
case x if x > 0:
print('positive')All lessons in this course
- match and case Basics
- Matching Sequences and Mappings
- Class Patterns
- Guards and Wildcards