|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# Basic match statement day = 3 match day: case 1: print("Monday") case 2: print("Tuesday") case 3: print("Wednesday") case _: print("Other day") # Match with multiple values status = 200 match status: case 200 | 201: print("Success") case 400 | 404: print("Client Error") case 500: print("Server Error") case _: print("Unknown status") # Pattern matching point = (0, 0) match point: case (0, 0): print("Origin") case (0, y): print(f"Y-axis at {y}") case (x, 0): print(f"X-axis at {x}") case _: print("Somewhere else") Output: Wednesday Success Origin ► Important Points ✓ Requires Python 3.10 or higher ✓ Much cleaner than long if-elif chains ✓ Supports advanced pattern matching ✓ case _: is the default catch-all ✓ Can match multiple values with | ✓ More maintainable for complex branching ► Remember ✓ Use match when you have many conditions ✓ Always include case _: for default behavior ✓ Pattern matching is more powerful than simple values ✓ Falls through to first matching case only ✓ Improves code readability significantly ■ Practice Challenge 1. Create a match statement for grade conversion (A-F to GPA) 2. Build a calculator using match for operations (+, -, *, /) 3. Match HTTP methods (GET, POST, PUT, DELETE) to actions |
