菜鸟教程《Python 3 教程》笔记(10)
笔记带有个人侧重点,不追求面面俱到。
10 条件控制
10.1 match…case
Python 3.10 增加了 match...case
的条件判断。match
后的对象会依次与 case
后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,_
可以匹配一切。
语法:
match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
10.1.1 基本模式匹配
x = 10
match x:
case 10:
print("x is 10")
case 20:
print("x is 20")
case _:
print("x is something else")
10.1.2 序列模式匹配
point = (2, 3)
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Point is on the Y axis at {y}")
case (x, 0):
print(f"Point is on the X axis at {x}")
case (x, y):
print(f"Point is at ({x}, {y})")
case _:
print("Not a point")
10.1.3 对象模式匹配
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(0, 3)
match p:
case Point(x=0, y=y):
print(f"Point is on the Y axis at {y}")
case Point(x=x, y=0):
print(f"Point is on the X axis at {x}")
case Point(x, y):
print(f"Point is at ({x}, {y})")
case _:
print("Not a point")
10.1.4 OR 模式
x = 2
match x:
case 1 | 2 | 3:
print("x is 1, 2, or 3")
case _:
print("x is something else")
10.1.5 守卫
x = 10
match x:
case x if x > 5:
print("x is greater than 5")
case _:
print("x is 5 or less")