defhandle_command(command): match command.split(): case ["quit"]: print("Goodbye!") case ["look"]: print("You see nothing special.") case ["go", direction]: print(f"You go {direction}") case ["take", item]: print(f"You take the {item}") case _: print("Unknown command")
handle_command("quit") # Goodbye! handle_command("go north") # You go north handle_command("take sword") # You take the sword
2. 解构列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defprocess_points(points): match points: case []: return"No points" case [x]: returnf"Single point at {x}" case [x, y]: returnf"Points at {x} and {y}" case [x, y, z]: returnf"Points at {x}, {y}, and {z}" case _: returnf"Many points: {len(points)} total"
print(process_points([])) # No points print(process_points([1])) # Single point at 1 print(process_points([1, 2])) # Points at 1 and 2
defdescribe_shape(shape): match shape: case Point(x=0, y=0): return"Origin point" case Point(x=x, y=y): returnf"Point at ({x}, {y})" case Rectangle(width=w, height=h) if w == h: returnf"Square with side {w}" case Rectangle(width=w, height=h): returnf"Rectangle {w}x{h}"
print(describe_shape(p1)) # Origin point print(describe_shape(p2)) # Point at (3, 4) print(describe_shape(r1)) # Square with side 5 print(describe_shape(r2)) # Rectangle 4x6
四、添加条件
1. guard子句
使用if添加条件:
1 2 3 4 5 6 7 8 9 10 11 12
defclassify_number(n): match n: case x if x < 0: return"Negative" case0: return"Zero" case x if x > 0: return"Positive"
print(classify_number(-5)) # Negative print(classify_number(0)) # Zero print(classify_number(10)) # Positive
2. 复杂的guard条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defhandle_login(username, password): match (username, password): case ("admin", "admin123"): return"Admin login" case ("user", p) iflen(p) >= 8: return"Valid user login" case ("user", _): return"Invalid password" case _: return"Unknown user"
defparse_message(msg): """解析不同类型的消息""" match msg.split(maxsplit=1): case ["HELLO"]: return"Hello there!" case ["HELLO", name]: returnf"Hello, {name}!" case ["GOODBYE"]: return"Goodbye!" case ["ECHO", text]: return text case ["REPEAT", n, text] if n.isdigit(): return text * int(n) case _: return"Unknown command"
defshape_area(shape): """计算不同形状的面积""" match shape: case {"type": "circle", "radius": r}: import math return math.pi * r ** 2 case {"type": "rectangle", "width": w, "height": h}: return w * h case {"type": "triangle", "base": b, "height": h}: return0.5 * b * h case _: returnNone
defhttp_error(status): """返回HTTP错误信息""" match status: case400: return"Bad Request" case401 | 403: return"Unauthorized or Forbidden" case404: return"Not Found" case500 | 502 | 503: return"Server Error" case _: return"Unknown Error"