Learn programming concepts interactively
Matched Pattern:
No pattern matched
Enter data to see pattern matching
# Python Pattern Matching - Interactive Examples# Learn match statements through hands-on practice (Python 3.10+)# === DATA STRUCTURE MATCHER ===# Example of pattern matching with different data typesdata = nullmatch data:case []:result = "Empty list detected"case [single]:result = `Single item list: ${single}`case [first, second]:result = `Two items: ${first}, ${second}`case [first, *rest]:result = `First: ${first}, Rest: ${len(rest)} items`case (0, 0):result = "Origin point detected"case (x, 0) if x > 0:result = "Positive X-axis point"case (0, y) if y > 0:result = "Positive Y-axis point"case (x, y):result = `Point at (${x}, ${y})`case _:result = "Unknown data type"print(f"Data pattern result: {result}")# === COMMAND PARSER ===# Example of literal pattern matchingcommand = "help"match command.lower().split():case ["start"]:action = "Starting system"case ["start", *args]:action = `Starting ${' '.join(args)}`case ["stop"]:action = "Stopping system"case ["restart"]:action = "Restarting system"case ["list", target]:action = `Listing ${target}`case ["delete", *items] if items:action = `Deleting: ${' '.join(items)}`case ["help"]:action = "Showing help"case _:action = "Unknown command"print(f"Command result: {action}")# === SHAPE CLASSIFIER ===# Example of pattern matching with guards and object patternsshape = {"type": "none", "properties": {}}match shape:case {"type": "circle", "properties": {"radius": r}} if r > 10:classification = "Large Circle"area = 3.14159 * r ** 2case {"type": "circle", "properties": {"radius": r}}:classification = "Small Circle"area = 3.14159 * r ** 2case {"type": "square", "properties": {"side": s}} if s > 10:classification = "Large Square"area = s ** 2case {"type": "square", "properties": {"side": s}}:classification = "Small Square"area = s ** 2case {"type": "triangle", "properties": {"base": b, "height": h}}:classification = "Triangle"area = 0.5 * b * hcase {"type": "polygon", "properties": {"sides": n}} if n > 6:classification = "Complex Polygon"area = None # Complex calculation neededcase _:classification = "Unknown Shape"area = Noneprint(f"Shape: {classification}, Area: {area}")# Key Pattern Matching Concepts:# - Literal patterns: case "start":# - Variable capture: case [first, *rest]:# - Guard conditions: case x if x > 10:# - Object patterns: case {"type": "user", "name": name}:# - Wildcard pattern: case _:# - Multiple patterns and complex matching
No operations yet
Start by adding or modifying elements