Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

While (循环)

🟦 1. 基本语法

while condition:
    # 循环体
else:
    # 条件不满足自动执行(可选)

注意:

  • 当 condition 为 False 时停止循环
  • else 只有循环 自然结束 才执行(不是被 break 终止)

🟩 2. 基础示例

i = 0
while i < 5:
    print(i)
    i += 1

🟦 3. while + else(Python 特有)

i = 0
while i < 3:
    print(i)
    i += 1
else:
    print("循环正常结束")

如果用 break 提前退出,else 不执行:

i = 0
while i < 3:
    break
else:
    print("不会执行")

🟩 4. 无限循环(常见)

while True:
    ...

常用于:

  • 服务常驻进程
  • 守护程序
  • 轮询任务
  • 消息队列消费

退出条件必须在循环体内控制:

while True:
    cmd = input("> ")
    if cmd == "exit":
        break

🟦 5. while 的常见控制语句

break:跳出整个循环

while True:
    if done:
        break

continue:跳到下一次循环

while i < 10:
    i += 1
    if i % 2 == 0:
        continue
    print(i)

🟩 6. while vs for

| 场景 | 用 for | 用 while | | 遍历列表 / 字典 / 字符串 | ✅ 推荐 | 不推荐 | | 明确次数(range) | ✅ 推荐 | 不推荐 | | 依靠“条件判断”循环 | 不适合 | ✅ 最适合 | | 无限循环 | 也可用 | ✅ 最常用 | | I/O 阻塞、轮询 | 可用 | ✅ 标准写法 |

总结:

  • 能用 for 就不用 while;
  • while 用于无法预先确定循环次数的逻辑。

🟦 7. 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+ 海象运算符)

🟦 8. 最佳实践(高质量代码)

① 避免无限循环没有出口

while True:
    ...

必须加 break 或 return。

② 优先使用 for

错误(不 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

⑤ while + sleep 模拟定时任务

import time

while True:
    run_job()
    time.sleep(60)

🟦 9. 速查表(收藏版)

功能 写法
基本循环 while condition:
无限循环 while True:
带 else while … else:
手动退出 break
跳过当前循环 continue
海象运算符 while x := func():
遍历文件流 while chunk := f.read(1024):
重试 while retries > 0: