Refine Patterns with Guards
Core idea
A guard is an if expression after a case pattern. Python checks the pattern first; if it succeeds, the guard may use captured names. A truthy guard selects the case, while a falsey guard allows subsequent cases to be considered. Exceptions from guard expressions propagate normally. Guards work well for ranges and comparisons that literal patterns cannot express directly.
match 82: case n if n >= 80: print("high") case _: print("normal")The capture supplies n before the comparison. This example assumes a number.
Continue after a false guard
match ["stock", 0]: case ["stock", n] if n > 0: print("available") case ["stock", n]: print("empty or invalid")The first pattern matches but its guard is false; the second case runs.
Skip a guard after pattern failure
def check(): print("guard evaluated") return Truematch ["other", 8]: case ["stock", n] if check(): print(n) case _: print("other")The literal tag fails, so check is never called.
Common mistake
Capturing a value does not check its type. If you accept mixed inputs, use a suitable type check before numeric comparisons. Avoid guards that depend on hidden side effects.
Practice
For integer input, distinguish negative, zero and positive values using guarded captures and a fallback. Test each boundary.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Apply guards
Check your understanding of guards.
What is printed?
match 79: case n if n >= 80: print("high") case _: print("normal")What is printed?
match ["stock", 3]: case ["stock", n] if n > 0: print("yes") case _: print("no")What is printed?
def check(): print("checked") return Truematch "idle": case "start" if check(): print("start") case _: print("other")What happens if a guard raises an exception?