第 4 章 控制流:条件、循环与结构匹配
4.1 条件语句 if elif else
Python 用缩进(4 空格)表示代码块,冒号 : 开启块:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "D"
print(grade)
要点:
条件不需要括号,冒号和缩进必须有;
条件按顺序求值,命中即止;
任何对象都能做条件(见第 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)
range(2, 10, 2)
for i in range(3):
print(i)
enumerate:同时要下标和值
for i, fruit in enumerate(fruits, start=1):
print(i, fruit)
不要写 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))
循环控制:break continue else
for n in [1, 2, 3, 4]:
if n == 3:
break
if n % 2 == 0:
continue
print(n)
for...else 是 Python 特色:循环未被 break 中断(正常跑完)时执行 else:
for n in nums:
if n == target:
print("found")
break
else:
print("not found")
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 做结构匹配。
下一章:函数——参数、作用域、匿名函数与装饰器入门。