16.1 什么是 while 循环? #
while 在条件为真时重复执行代码块;条件变假后退出。适合「次数不确定、直到某条件成立」的场景。
count = 1
while count <= 5:
print(count)
count += 1 # 必须更新条件相关变量,否则会死循环16.2 基本语法 #
while 条件:
# 循环体(缩进 4 空格)16.3 break 与 continue #
| 语句 | 作用 |
|---|---|
break |
立即结束整个循环 |
continue |
跳过本次剩余代码,进入下一轮 |
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue # 跳过偶数
if n > 5:
break # 大于 5 就结束
print(n)16.4 常见模式:while True + break #
项目里常用于重试、轮询、简易菜单:循环体里用 if 判断何时 break。
while True:
choice = input("输入 q 退出: ")
if choice == "q":
break
print(f"你输入了: {choice}")def call_api():
print("call_api")
return False
# 重试直到成功
attempts = 0
max_attempts = 3
while attempts < max_attempts:
ok = call_api() # 假设返回是否成功
if ok:
break
attempts += 116.5 while 与 for 怎么选 #
| 场景 | 推荐 |
|---|---|
| 遍历列表、字典、固定次数 | for(更常见) |
| 条件未知、直到满足才停 | while |
| 无限服务循环 + 内部 break | while True |
# 遍历用 for,不要用 while + index
for fruit in ["苹果", "香蕉"]:
print(fruit)16.6 项目开发要点 #
- 必须有退出路径:条件最终会变假,或
break/return,避免死循环 - 遍历集合优先
for:while index < len(lst)易错,用for item in lst while True要克制:只在结构清晰时使用,并保证有break- 少用
while的else:仅在循环「未 break 正常结束」时执行,项目里很少用 - Web/接口开发:大量循环被框架、数据库游标、
for迭代替代;while多见于重试、消费队列、脚本 - 长时间循环:注意超时、最大次数,避免阻塞请求(异步、任务队列后续会讲)