0Pricing
Python Academy · Lesson

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

  1. match and case Basics
  2. Matching Sequences and Mappings
  3. Class Patterns
  4. Guards and Wildcards
← Back to Python Academy