0Pricing
Python Academy · Lesson

Guards and Wildcards

Add conditions and catch-all cases.

Guards and Wildcards is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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')

Guards Use Captured Names

A guard can reference variables bound by the pattern. Here the captured pair is checked for equality.

point = [3, 3]

match point:
    case [x, y] if x == y:
        print('on the diagonal')
    case [x, y]:
        print('off the diagonal')

If the Guard Fails

If the structure matches but the guard is false, matching continues to the next case rather than stopping.

value = 5

match value:
    case n if n > 100:
        print('big')
    case n:
        print('fell through to here:', n)

Guards with Class Patterns

Guards combine with any pattern type, including class patterns, for precise conditions on object attributes.

from dataclasses import dataclass

@dataclass
class Order:
    total: float

def discount(order):
    match order:
        case Order(total=t) if t > 100:
            return 'free shipping'
        case Order():
            return 'standard shipping'

print(discount(Order(150)))
print(discount(Order(50)))

The Wildcard Recap

The lone underscore _ matches anything and binds nothing. As the final case it handles everything not caught earlier.

x = 'unexpected'

match x:
    case 'a':
        print('letter a')
    case _:
        print('catch-all')

Capture vs Wildcard

A named capture also matches anything but keeps the value, while _ discards it. Use a name when you need the value in the body.

value = 42

match value:
    case 0:
        print('zero')
    case other:        # capture: keeps the value
        print('value was', other)

Wildcards Inside Patterns

The underscore can appear inside larger patterns to ignore parts you do not care about.

record = ('user', 42, 'ignore_me')

match record:
    case ('user', user_id, _):
        print('user id:', user_id)

Combining OR, Guards, and Wildcards

These features compose. An OR pattern, then a guard, then a final wildcard makes for an expressive classifier.

def classify(n):
    match n:
        case 0 | 1:
            return 'binary digit'
        case x if x % 2 == 0:
            return 'even'
        case _:
            return 'odd'

print(classify(0))
print(classify(4))
print(classify(7))

Exhaustiveness

Unlike some languages, Python does not force a match to be exhaustive. If no case matches, the statement simply does nothing. Add a final case _ when you want to guarantee a branch always runs.

color = 'purple'
result = 'no match'

match color:
    case 'red':
        result = 'stop'
    case 'green':
        result = 'go'

print(result)

Guards on Destructured Data

Guards pair naturally with sequence and mapping patterns, letting you test the values you just pulled out.

data = [10, 20]

match data:
    case [a, b] if a + b > 25:
        print('sum is large')
    case [a, b]:
        print('sum is small')

Quick Check

What happens when a pattern matches structurally but its guard condition is false?

Recap

You learned to add conditions and catch-all cases.

  • Guards add an if test that can use captured names.
  • A failing guard falls through to the next case.
  • _ matches and discards; a name captures.
  • Add a final case _ for a guaranteed branch.

Frequently asked questions

Is the “Guards and Wildcards” lesson free?

Yes — the full text of “Guards and Wildcards” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Guards and Wildcards”?

Add conditions and catch-all cases. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Guards and Wildcards” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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