条件控制

# if 条件控制
num = 3
if num == 0:
    print(f"0 num是{num}")
elif num == 1:
    print(f"1 num是{num}")
elif num == 2:
    print(f"2 num是{num}")
elif num == 3:
    print(f"3 num是{num}")
elif num == 4:
    print(f"4 num是{num}")
else:
    print("以上条件都不对!")


# match 用法
# 在Python中,match 语句是在Python 3.10及更高版本中引入的一个新特性,
# 它提供了一种模式匹配(Pattern Matching)的简洁方式,用于从数据结构
# (如元组、列表、字典等)中提取信息,并根据匹配的模式执行相应的代码块。
# 这种语法与一些其他编程语言(如Rust、Swift)中的模式匹配功能相似。

# 1. 匹配字面值
x = 42  
match x:  
    case 42:  
        print("Found the answer!")  
    case y if y > 40:  
        print(f"Got a big number {y}")  
    case _:  
        print("No match")
# 输出 Found the answer!

# 2. 匹配序列和映射
data = (1, 2, 3)  
match data:  
    case (0, *rest):  
        print("Found a leading zero:", rest)  
    case (a, b, c) if a == b == c:  
        print("Found three equal numbers:", a)  
    case (a, b, c):  
        print("Found three numbers:", a, b, c)  
    case _:  
        print("Not sure what this is")  
# 输出 Found three numbers: 1 2 3

# 3. 匹配字典  
person = {"name": "Alice", "age": 30}  
match person:  
    case {"name": name, "age": age}:  
        print(f"Name: {name}, Age: {age}")  
    case _:  
        print("Not a person")
# 输出 Name: Alice, Age: 30

# 4. 嵌套模式
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 (x, y):  
        print(f"Point ({x}, {y})")
# 输出 Origin

# 注意事项
# match 语句的结束是由其对应的 : 开始的,而不是通过缩进来定义的。
# 每个 case 语句后面跟随的模式可以是字面量、变量、序列(如元组或列表)、映射(如字典)、类实例或更复杂的模式(使用 | 表示“或”的联合模式,使用 * 表示“任意数量”的序列模式)。
# _ 是一个特殊的模式,代表任何值,通常用作默认情况。
# 在Python中,match 语句提供了比传统 if-elif-else 语句更强大和更清晰的模式匹配功能,尤其是在处理复杂的数据结构和条件时。
# 总的来说,match 语句是Python 3.10及以上版本中引入的一个非常有用的新特性,它提供了一种更加直观和强大的方式来处理条件逻辑和数据匹配。
posted @ 2024-07-29 14:05  文武双全·墨海纵横  阅读(36)  评论(0)    收藏  举报