match — Intermediate Playground
Begins a structural pattern matching block (3.10+)
Python Playground
# Sequence patterns
point = (3, 4)
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"On x-axis at {x}")
case (0, y):
print(f"On y-axis at {y}")
case (x, y):
print(f"Point at ({x}, {y})")
# Mapping patterns
config = {"type": "circle", "radius": 5}
match config:
case {"type": "circle", "radius": r}:
print(f"Circle with radius {r}, area = {3.14 * r**2:.1f}")
case {"type": "rectangle", "width": w, "height": h}:
print(f"Rectangle {w}x{h}, area = {w*h}")
# Nested patterns
data = {"user": {"name": "Alice", "role": "admin"}}
match data:
case {"user": {"name": str(name), "role": "admin"}}:
print(f"Admin: {name}")
case {"user": {"name": str(name)}}:
print(f"User: {name}")
Output
Click "Run" to execute your code
match can destructure sequences, mappings, and nested structures. Capture variables extract values from the matched structure.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?