2.python流程控制与模式匹配

2.python流程控制与模式匹配

_

1. 条件判断:if, elif, else

条件判断是程序逻辑的基石。Python 的语法设计强调可读性,使用缩进来表示代码块。

1.1 基础语法

score = 85

if score >= 90:
    print("优秀")
elif score >= 60:
    print("及格")
else:
    print("不及格")

1.2 真值测试 (Truthiness)

在 Python 中,不仅仅是 TrueFalse,很多对象在布尔上下文中都有隐含的真值。

  • 视为 False 的值0, 0.0, "" (空字符串), [] (空列表), {} (空字典), None

  • 视为 True 的值:非零数字,非空容器,非 None 对象。

✅ 推荐写法:直接利用真值测试,代码更简洁。

name = ""

# ❌ 冗余写法
if name != "":
    print("名字不为空")

# ✅ 推荐写法
if name:
    print("名字不为空")

# 检查列表是否为空
items = []
if items:  # 如果列表有元素
    print(f"共有 {len(items)} 个物品")
else:
    print("列表为空")

1.3 避免过度嵌套

深层嵌套的 if 会降低可读性(俗称“箭头代码”)。建议使用 守卫子句 (Guard Clauses) 提前返回。

# ❌ 过度嵌套
def process_user(user):
    if user:
        if user.is_active:
            if user.has_permission:
                print("处理逻辑...")
            else:
                print("无权限")
        else:
            print("未激活")
    else:
        print("用户不存在")

# ✅ 守卫子句 (提前返回)
def process_user(user):
    if not user:
        print("用户不存在")
        return
    
    if not user.is_active:
        print("未激活")
        return
    
    if not user.has_permission:
        print("无权限")
        return
        
    print("处理逻辑...")

2. 循环结构:for 与 while

2.1 for 循环:遍历 iterable

Python 的 for 循环本质上是 foreach,用于遍历序列(列表、字符串、元组等)或迭代器。

# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# 遍历范围 (range)
for i in range(5):  # 0 到 4
    print(i)

# 同时获取索引和值 (enumerate)
# ❌ 不推荐:range(len(items))
# ✅ 推荐:enumerate
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

2.2 while 循环:条件驱动

当循环次数不确定,只依赖条件时使用 while

count = 0
while count < 5:
    print(count)
    count += 1  # 别忘了更新条件,否则死循环

2.3 循环控制:break, continue, else

  • break:立即终止整个循环。

  • continue:跳过本次迭代,进入下一次。

  • elsePython 特有特性。当循环 正常结束(没有被 break 打断)时执行。

# 查找质数示例
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(f"{n} 等于 {x} * {n//x}")
            break
    else:
        # 如果没有 break,说明是质数
        print(f"{n} 是质数")

💡 提示:循环的 else 子句在实际业务中用得较少,但理解它有助于读懂某些高级算法代码。


3. ✨ 现代模式匹配 (Structural Pattern Matching)

这是 Python 3.10 引入的最重要特性之一。虽然它看起来像其他语言的 switch-case,但它的功能要强大得多。它不仅可以匹配值,还可以匹配 数据结构解构赋值

3.1 基础语法

status = 404

match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Server Error")
    case _:  # 默认情况,相当于 else
        print("Unknown Status")

3.2 结构匹配与解构 (核心优势)

match-case 最强大的地方在于它可以匹配列表、元组、字典的结构,并直接提取变量。

command = ["add", 10, 20]

match command:
    # 匹配列表结构,并将值赋给 x, y
    case ["add", x, y]:
        print(f"Result: {x + y}")
    
    # 匹配特定值
    case ["quit"]:
        print("Quitting...")
        
    # 匹配字典结构
    case {"action": "save", "file": filename}:
        print(f"Saving to {filename}")
        
    case _:
        print("Unknown command")

3.3 守卫条件 (Guards)

你可以在 case 后面添加 if 条件,进一步过滤匹配。

point = (10, 0)

match point:
    case (0, 0):
        print("原点")
    case (0, y):
        print(f"Y 轴上的点:{y}")
    case (x, 0):
        print(f"X 轴上的点:{x}")
    case (x, y) if x == y:
        print(f"在 y=x 线上:{x}")
    case (x, y):
        print(f"普通点:{x}, {y}")

3.4 匹配类实例

如果你定义了类,match 可以直接匹配类的属性。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)

match p:
    case Point(x=0, y=0):
        print("原点")
    case Point(x=x, y=y):
        print(f"坐标:{x}, {y}")

4. 最佳实践:if-elif vs match-case

什么时候该用 match-case?什么时候该用传统的 if-elif

场景

推荐方案

理由

简单的布尔判断

if-elif

例如 if x > 0 and y < 0if 更直观。

范围判断

if-elif

例如 if 60 <= score < 90match 不擅长处理范围。

单一变量多值匹配

match-case

例如状态码、命令字,代码更整洁。

复杂结构解构

match-case

例如解析嵌套列表、字典、对象,match 能大幅减少代码量。

需要提取数据

match-case

匹配的同时直接赋值变量,无需额外索引操作。

重构示例:从 if-elif 到 match-case

❌ 旧式写法 (冗长)

def handle_event(event):
    if event.type == "click":
        x = event.data["x"]
        y = event.data["y"]
        print(f"Clicked at {x}, {y}")
    elif event.type == "keypress":
        key = event.data["key"]
        print(f"Key pressed: {key}")
    elif event.type == "resize":
        w = event.data["w"]
        h = event.data["h"]
        print(f"Resized to {w}x{h}")
    else:
        print("Unknown event")

✅ 现代写法 (清晰)

def handle_event(event):
    match event:
        case {"type": "click", "data": {"x": x, "y": y}}:
            print(f"Clicked at {x}, {y}")
        case {"type": "keypress", "data": {"key": key}}:
            print(f"Key pressed: {key}")
        case {"type": "resize", "data": {"w": w, "h": h}}:
            print(f"Resized to {w}x{h}")
        case _:
            print("Unknown event")

注意:现代写法直接在匹配过程中完成了数据提取,无需额外的 event.data["x"] 访问。


5. 本章实战练习

为了巩固本章内容,请完成以下任务:

  1. 成绩评级系统

    • 使用 input() 获取用户输入的成绩(0-100)。

    • 使用 if-elif-else 判断等级(A: 90+, B: 80+, C: 60+, D: 不及格)。

    • 要求:处理用户输入非数字的情况(暂时可以用 try-exceptisdigit() 简单处理)。

  2. 命令解析器 (使用 match-case)

    • 定义一个列表模拟用户命令,例如 ["login", "admin", "123456"]["logout"]

    • 使用 match-case 解析该列表。

    • 如果是 login,提取用户名和密码并打印。

    • 如果是 logout,打印“已退出”。

    • 其他情况打印“未知命令”。

  3. 循环挑战

    • 使用 for 循环和 range 打印 99 乘法表。

    • 使用 while 循环实现一个简单的计数器,当计数到 5 时使用 break 退出。

1.python基础语法与现代交互 (Basics & Modern REPL) 2026-03-10
3.python数据结构与类型提示心智 2026-03-10

评论区