Control Flow
Match Statements
Use match when the shape of a value is the decision. This command is a dictionary with an action and coordinates; the first case checks that shape and binds x and y.
Source
command = {"action": "move", "x": 3, "y": 4}
match command:
case {"action": "move", "x": x, "y": y}:
print(f"move to {x},{y}")Output
move to 3,4Other cases describe other valid shapes. This complete fragment changes the command so the quit case is the first matching pattern.
Source
command = {"action": "quit"}
match command:
case {"action": "move", "x": x, "y": y}:
print(f"move to {x},{y}")
case {"action": "quit"}:
print("quit")Output
quitBroader patterns and the _ catch-all belong after specific cases. This fragment extracts an unknown action before the final fallback would run.
Source
command = {"action": "jump"}
match command:
case {"action": "move", "x": x, "y": y}:
print(f"move to {x},{y}")
case {"action": "quit"}:
print("quit")
case {"action": action}:
print(f"unknown action: {action}")
case _:
print("invalid command")Output
unknown action: jumpNotes
matchcompares structure, not just equality.- Patterns can bind names such as
xandywhile matching. - Put the catch-all
_case last, because cases are tried from top to bottom.
See also
- related: Conditionals
- related: Advanced Match Patterns
- next depth: Structured Data Shapes
- next depth: Dictionaries
Run the complete example
Expected output
move to 3,4
Execution time appears here after you run the example.