1. 什么是 while 循环? #
while 在条件为真时重复执行代码块;条件变假后退出。
- 适合「次数不确定、直到某条件成立」的场景。
count = 1
while count <= 5:
print(count)
count += 1
2. 基本语法 #
- 结构为
while 条件:,下一行起是缩进的循环体。
while 条件:
3. break 与 continue #
- 循环体内可用
break 立即结束整个循环,或用 continue 跳过本次剩余代码。
| 语句 |
作用 |
break |
立即结束整个循环 |
continue |
跳过本次剩余代码,进入下一轮 |
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue
if n > 5:
break
print(n)
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 += 1
5. while 与 for 怎么选 #
- 遍历已知集合优先用
for;条件驱动、次数不确定时用 while。
| 场景 |
推荐 |
| 遍历列表、字典、固定次数 |
for(更常见) |
| 条件未知、直到满足才停 |
while |
| 无限服务循环 + 内部 break |
while True |
for fruit in ["苹果", "香蕉"]:
print(fruit)
6. 项目开发要点 #
- 必须有退出路径:条件最终会变假,或
break/return,避免死循环。
- 遍历集合优先
for:while index < len(lst) 易错,用 for item in lst。
while True 要克制:只在结构清晰时使用,并保证有 break。
- 少用
while 的 else:仅在循环「未 break 正常结束」时执行,项目里很少用。
- Web/接口开发:大量循环被框架、数据库游标、
for 迭代替代;while 多见于重试、消费队列、脚本。
- 长时间循环:注意超时、最大次数,避免阻塞请求(异步、任务队列后续会讲)。