Control Flow
Advanced Match Patterns
Sequence patterns match by position. A guard after if adds a condition that must also be true.
Source
def describe(command):
match command:
case ["move", x, y] if x >= 0 and y >= 0:
return f"move to {x},{y}"
case ["quit" | "exit"]:
return "stop"
case ["echo", *words]:
return " ".join(words)
case _:
return "unknown"
print(describe(["move", 2, 3]))Output
move to 2,3An OR pattern accepts several alternatives in one case. A star pattern captures the rest of a sequence.
Source
print(describe(["exit"]))
print(describe(["echo", "hello", "python"]))Output
stop
hello pythonThe wildcard _ catches values that did not match earlier cases. Here the guard rejects the negative coordinate.
Source
print(describe(["move", -1, 3]))Output
unknownNotes
- Use
case _as a wildcard fallback. - Guards refine a pattern after the structure matches.
- OR patterns and star patterns keep shape-based branches compact.
See also
- related: Match Statements
- next depth: Tuples
- next depth: Classes
Run the complete example
Expected output
move to 2,3
stop
hello python
unknown
Execution time appears here after you run the example.