While (循环)
while condition:
# 循环体
else:
# 条件不满足自动执行(可选)
注意:
- 当 condition 为 False 时停止循环
- else 只有循环 自然结束 才执行(不是被 break 终止)
i = 0
while i < 5:
print(i)
i += 1
i = 0
while i < 3:
print(i)
i += 1
else:
print("循环正常结束")
如果用 break 提前退出,else 不执行:
i = 0
while i < 3:
break
else:
print("不会执行")
while True:
...
常用于:
- 服务常驻进程
- 守护程序
- 轮询任务
- 消息队列消费
退出条件必须在循环体内控制:
while True:
cmd = input("> ")
if cmd == "exit":
break
break:跳出整个循环
while True:
if done:
break
continue:跳到下一次循环
while i < 10:
i += 1
if i % 2 == 0:
continue
print(i)
| 场景 | 用 for | 用 while | | 遍历列表 / 字典 / 字符串 | ✅ 推荐 | 不推荐 | | 明确次数(range) | ✅ 推荐 | 不推荐 | | 依靠“条件判断”循环 | 不适合 | ✅ 最适合 | | 无限循环 | 也可用 | ✅ 最常用 | | I/O 阻塞、轮询 | 可用 | ✅ 标准写法 |
总结:
- 能用 for 就不用 while;
- while 用于无法预先确定循环次数的逻辑。
while True:
data = socket.recv(1024)
if not data:
break
while True:
msg = redis.lpop("queue")
if msg:
process(msg)
retries = 3
while retries > 0:
if call_api():
break
retries -= 1
while chunk := f.read(1024):
process(chunk)
(Python 3.8+ 海象运算符)
while True:
...
必须加 break 或 return。
错误(不 pythonic):
i = 0
while i < len(items):
print(items[i])
i += 1
正确:
for item in items:
print(item)
传统写法:
line = f.readline()
while line:
...
line = f.readline()
Pythonic:
while line := f.readline():
...
常见错误:
i = 0
while i < 5:
print(i)
# 忘记 i += 1
import time
while True:
run_job()
time.sleep(60)
| 功能 | 写法 |
|---|---|
| 基本循环 | while condition: |
| 无限循环 | while True: |
| 带 else | while … else: |
| 手动退出 | break |
| 跳过当前循环 | continue |
| 海象运算符 | while x := func(): |
| 遍历文件流 | while chunk := f.read(1024): |
| 重试 | while retries > 0: |