def http_error(status):
match status:
case 400:
return "Bad Request"
case 404:
return "Not Found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
print(http_error(404)) # 输出:Not Found
def process_number(x):
match x:
case 1:
print("One")
case 2:
print("Two")
case _:
print("Something else")
process_number(1) # 输出:One
process_number(3) # 输出:Something else
def point_info(point):
match point:
case (0, 0):
return "Origin"
case (0, y):
return f"Y-axis at {y}"
case (x, 0):
return f"X-axis at {x}"
case (x, y):
return f"Point at ({x}, {y})"
print(point_info((0, 0))) # 输出:Origin
print(point_info((0, 5))) # 输出:Y-axis at 5
print(point_info((3, 0))) # 输出:X-axis at 3
print(point_info((2, 3))) # 输出:Point at (2, 3)
def process_list(lst):
match lst:
case []:
return "Empty list"
case [x]:
return f"Single element: {x}"
case [x, y]:
return f"Two elements: {x} and {y}"
case [x, y, *rest]:
return f"First two: {x}, {y}, and the rest: {rest}"
print(process_list([])) # 输出:Empty list
print(process_list([1])) # 输出:Single element: 1
print(process_list([1, 2])) # 输出:Two elements: 1 and 2
print(process_list([1, 2, 3, 4])) # 输出:First two: 1, 2, and the rest: [3, 4]
def process_dict(d):
match d:
case {"name": name, "age": age}:
return f"Name: {name}, Age: {age}"
case {"name": name}:
return f"Name: {name}"
case _:
return "Unknown structure"
print(process_dict({"name": "Alice", "age": 30})) # 输出:Name: Alice, Age: 30
print(process_dict({"name": "Bob"})) # 输出:Name: Bob
print(process_dict({"age": 25})) # 输出:Unknown structure
def process_number(x):
match x:
case x if x > 0:
return "Positive"
case x if x < 0:
return "Negative"
case 0:
return "Zero"
print(process_number(10)) # 输出:Positive
print(process_number(-5)) # 输出:Negative
print(process_number(0)) # 输出:Zero
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def process_point(p):
match p:
case Point(x=0, y=0):
return "Origin"
case Point(x, y):
return f"Point at ({x}, {y})"
p1 = Point(0, 0)
p2 = Point(1, 2)
print(process_point(p1)) # 输出:Origin
print(process_point(p2)) # 输出:Point at (1, 2)