第 4 章 控制流:条件、循环与结构匹配

4.1 条件语句 if elif else

Python 用缩进(4 空格)表示代码块,冒号 : 开启块:

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:        # elif = else if
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "D"

print(grade)             # B

要点:

  • 条件不需要括号,冒号和缩进必须有;

  • 条件按顺序求值,命中即止;

  • 任何对象都能做条件(见第 2 章真值测试)。

三元表达式(条件表达式)

status = "成年" if age >= 18 else "未成年"

嵌套与提前返回

深层嵌套是可读性杀手,优先提前返回/继续(guard clause):

# 不推荐
def check(user):
    if user is not None:
        if user.is_active:
            if user.age >= 18:
                return "ok"
    return "rejected"

# 推荐
def check(user):
    if user is None or not user.is_active:
        return "rejected"
    if user.age < 18:
        return "rejected"
    return "ok"

4.2 for 循环:遍历可迭代对象

Python 的 for 是遍历(for-each),不是计数循环:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

for ch in "Python":          # 字符串也可遍历
    print(ch)

for key, value in {"a": 1}.items():   # 遍历字典
    print(key, value)

range:需要下标/次数时

range(5)         # 0,1,2,3,4(惰性序列,含头不含尾)
range(2, 10, 2)  # 2,4,6,8(起、止、步长)

for i in range(3):
    print(i)             # 0 1 2

enumerate:同时要下标和值

for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
# 1 apple
# 2 banana
# 3 cherry

不要写 for i in range(len(fruits)): print(fruits[i])——这是把 C 的习惯带进来,Pythonic 写法就是直接遍历,需要下标用 enumerate。

zip:并行遍历多个序列

names = ["Alice", "Bob"]
scores = [90, 85]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

dict(zip(names, scores))   # {'Alice': 90, 'Bob': 85} 快速造字典

循环控制:break continue else

for n in [1, 2, 3, 4]:
    if n == 3:
        break          # 终止整个循环
    if n % 2 == 0:
        continue       # 跳过本次,进入下一轮
    print(n)           # 1

for...else 是 Python 特色:循环未被 break 中断(正常跑完)时执行 else:

for n in nums:
    if n == target:
        print("found")
        break
else:
    print("not found")   # 没 break 才会走到这里

4.3 while 循环

不知道循环次数、按条件重复时用 while:

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

典型用法:

while True:                  # 常见于主循环/输入校验
    cmd = input("> ")
    if cmd == "quit":
        break

4.4 推导式替代简单循环

简单"收集/过滤"场景,推导式比循环更清晰:

# 循环写法
result = []
for x in range(10):
    if x % 2 == 0:
        result.append(x * x)

# 等价推导式
result = [x * x for x in range(10) if x % 2 == 0]

4.5 结构化模式匹配 match / case(Python 3.10+)

类似其他语言的 switch,但强大得多——可解构:

def handle(command):
    match command.split():
        case ["quit"]:
            return "bye"
        case ["load", filename]:
            return f"loading {filename}"
        case ["move", x, y] if x.isdigit() and y.isdigit():   # 守卫条件
            return f"move to ({x}, {y})"
        case _:                                    # 默认分支
            return "unknown"

还能匹配类型与结构:

match point:
    case (0, 0):               print("原点")
    case (0, y):               print(f"y 轴上,y={y}")
    case (x, y) if x == y:     print("对角线")
    case [x, y]:               print(f"二维点 ({x}, {y})")
    case {"name": n}:          print(f"字典键 name={n}")
    case Person(name=n):       print(f"数据类实例 name={n}")

低版本 Python(< 3.10)请用 if/elif 链或字典分发。

4.6 循环性能与习惯提醒

  • 循环内别做重复的不变计算,提到循环外;

  • 字符串拼接用 "".join(list),不要在循环里 s += x(字符串不可变,反复拼接是 O(n²));

  • 大数据判断成员用 set/dict,不要遍历 list;

  • 死循环在 REPL/脚本里按 Ctrl-C 中断。

4.7 本章小结

  • if/elif/else + 缩进是条件控制全部;

  • for 遍历可迭代对象;要下标用 enumerate,并行用 zip,计数用 range;

  • while 按条件循环;for...else 在未 break 时执行;

  • 3.10+ 可用 match/case 做结构匹配。

下一章:函数——参数、作用域、匿名函数与装饰器入门。

Python3 基础知识 / 第 4 章 控制流:条件、循环与结构匹配 0 字 0 行 cosolar
2026-09-17T11:10:47.688808676Z 2026-09-17T11:25:54.019985957Z