Python while 循环:根据条件重复执行任务

更新于 2026-01-11

Leodanis Pozo Ramos

Python 的 while 循环允许你在给定条件为真时,重复执行一段代码块。与 for 循环不同(后者用于已知次数的迭代),while 循环非常适合在迭代次数未知的情况下使用。

循环是 Python 中非常有用的结构,掌握如何编写和使用它们是你作为 Python 开发者的一项重要技能。

学完本教程后,你将理解以下内容:

  • while 是一个 Python 关键字,用于启动一个只要条件为真就重复执行代码块的循环。
  • while 循环在每次迭代开始时评估一个条件。如果条件为真,则执行循环体;否则终止循环。
  • 当迭代次数未知时(例如等待某个条件改变或持续处理用户输入),while 循环非常有用。
  • while True 在 Python 中会创建一个无限循环,直到遇到 break 语句或外部中断才会停止。
  • Python 没有内置的 do-while 循环,但你可以通过 while True 循环配合 break 语句来模拟它。

有了这些知识,你就能够编写高效的 while 循环,应对各种迭代需求。


初识 Python while 循环

在编程中,循环是一种控制流语句,允许你重复执行一组操作若干次。实践中,主要有两种类型的循环:

  • for 循环:通常用于已知迭代次数的情况,比如遍历具有固定数量元素的数据集合。
  • while 循环:通常用于迭代次数未知的情况,比如迭代次数取决于某个条件是否满足。

Python 同时支持这两种循环。本教程将重点介绍 while 循环。在 Python 中,当你需要重复执行一系列任务、但不知道具体要执行多少次时,通常会使用 while 循环。

Python 的 while 循环是一种复合语句,由一个头部和一个代码块组成,该代码块会一直运行,直到给定条件变为假。其基本语法如下:

while condition:
    <body>

在这个语法中:

  • condition 是一个表达式,循环会对其真假值进行评估。
  • 如果条件为真,则执行循环体;否则循环终止。
  • 循环体可以包含一个或多个语句,且必须正确缩进。

语法详解:

  • while:启动循环头部的关键字。
  • condition:定义退出条件的表达式,会被评估其“真值性”(truthiness)。
  • <body>:每次迭代中要执行的一个或多个语句。

示例:递减数字序列

下面是一个使用 while 循环打印递减数字的简单例子:

>>> number = 5
>>> while number > 0:
...     print(number)
...     number -= 1
...
5
4
3
2
1

在此示例中,number > 0 是循环条件。当该条件返回假值时,循环终止。循环体首先调用 print() 打印当前值,然后将 number 减 1。这一变化会影响下一次迭代中条件的评估结果。

只要条件为真,循环就会继续执行;一旦条件变为假,循环终止,程序继续执行循环体之后的第一条语句。本例中,当 number 变为小于或等于 0 时,循环结束。

⚠️ 注意:如果循环条件永远不会变为假,就会形成潜在的无限循环。例如:

>>> number = 5
>>> while number != 0:
...     print(number)
...     number -= 2
...
5
3
1
-1
-3
-5
...
# 永不停止!需按 Ctrl+C 终止

在这个例子中,由于每次减 2,number 永远不会等于 0,因此条件 number != 0 始终为真,导致无限循环。此时你可以按 Ctrl+C(在大多数操作系统上)来中断程序,这会引发 KeyboardInterrupt 异常。

另外要注意的是,while 循环先检查条件。如果一开始条件就是假的,循环体根本不会执行:

>>> number = 0
>>> while number > 0:
...     print(number)
...     number -= 1
...
# 无输出,因为条件一开始就为假

现在你已经掌握了 while 循环的基本语法,接下来我们将通过一些实际示例深入探讨其应用。


高级 while 循环语法

Python 的 while 循环具有一些高级特性,使其更加灵活和强大。这些特性在你需要精细控制循环流程时非常有用。

到目前为止,你看到的例子都是每次完整执行整个循环体。Python 提供了两个关键字来修改这种行为:

  • break:立即终止整个循环,程序继续执行循环之后的第一条语句。
  • continue:仅跳过当前迭代的剩余部分,直接回到循环头部重新评估条件。

此外,Python 的 while 循环还支持一个可选的 else 子句,当循环因条件变为假而自然结束时(而非因 break 提前退出),else 块中的代码会执行。

接下来,我们将分别介绍 breakcontinueelse 子句的用法。


break 语句:提前退出循环

使用 break 语句可以立即终止 while 循环,并让程序继续执行循环体之后的代码。

以下脚本演示了 break 的工作方式(break.py):

number = 6

while number > 0:
    number -= 1
    if number == 2:
        break
    print(number)

print("Loop ended")

number 变为 2 时,break 语句被执行,循环完全终止,程序跳转到最后一行的 print() 调用。

运行结果:

$ python break.py
5
4
3
Loop ended

循环正常打印数值,但当 number 达到 2 时,break 触发,循环结束,因此 2 和 1 不会被打印。

💡 提示break 通常应放在条件语句中。如果直接写在循环体中而不加条件判断,循环将在第一次迭代就终止,可能无法完成预期任务。


continue 语句:跳过当前迭代

continue 语句用于在满足特定条件时跳过当前迭代的剩余部分。

下面的脚本(continue.py)与上一节几乎相同,只是将 break 替换为 continue

number = 6

while number > 0:
    number -= 1
    if number == 2:
        continue
    print(number)

print("Loop ended")

输出结果:

$ python continue.py
5
4
3
1
0
Loop ended

这次,当 number 为 2 时,continue 被执行,跳过了 print(),所以 2 没有被打印。控制流返回到循环头部,重新评估条件,循环继续直到 number 为 0 后正常结束。


else 子句:在自然终止时执行任务

Python 允许在 while 循环末尾添加一个可选的 else 子句,语法如下:

while condition:
    <body>
else:
    <body>

else 块中的代码仅在循环因条件变为假而自然结束时执行不会在因 break 提前退出时执行

📌 注意:如果循环中没有 break 语句,那么 else 子句就没有存在的必要——直接把代码放在循环后面即可,这样更清晰。

实际应用场景:重试连接服务器

考虑以下模拟连接服务器的脚本(connection.py):

import random
import time

MAX_RETRIES = 5
attempts = 0

while attempts < MAX_RETRIES:
    attempts += 1
    print(f"Attempt {attempts}: Connecting to the server...")
    time.sleep(0.3)
    # 模拟连接成功(25% 概率)
    if random.choice([False, False, False, True]):
        print("Connection successful!")
        break
    print("Connection failed. Retrying...")
else:
    print("All attempts failed. Unable to connect.")
  • 如果连接成功,break 会提前退出循环,else 块不会执行
  • 如果所有重试都失败,循环自然结束(attempts >= MAX_RETRIES),else 块会执行,提示连接失败。

多次运行该脚本,你会看到不同的结果。


编写高效的 Python while 循环

编写 while 循环时,应确保其高效、可读且能正确终止

通常,当你需要重复执行一系列操作直到某个条件变为假(或保持为真)时,才应使用 while 循环。如果你要遍历一个可迭代对象(如列表、字符串等),应优先使用 for 循环

接下来,我们将学习如何有效使用 while 循环、避免无限循环、合理使用 break/continue,以及优雅地处理循环完成逻辑。


根据条件执行任务

while 循环常用于等待某个资源就绪后再继续执行,例如:

  • 等待文件被创建或填充
  • 检查服务器是否在线
  • 轮询数据库直到记录准备就绪
  • 确保 REST API 可用后再发送请求

示例:等待文件创建(check_file.py

import time
from pathlib import Path

filename = Path("hello.txt")

print(f"Waiting for {filename.name} to be created...")

while not filename.exists():
    print("File not found. Retrying in 1 second...")
    time.sleep(1)

print(f"{filename} found! Proceeding with processing.")
with open(filename, mode="r") as file:
    print("File contents:")
    print(file.read())
  • filename.exists() 返回 True 表示文件存在。
  • not filename.exists() 在文件不存在时为 True,循环继续。
  • 每次等待 1 秒后重试。

运行此脚本后,你可以在另一个终端中创建 hello.txt 文件。一旦文件出现,循环终止,程序读取并打印其内容。


处理未知数量的迭代

当你需要处理一个数量未知的数据流时,while 循环非常适用。此时可使用 while True 构造一个持续运行的循环,并在适当时候用 break 退出。

示例:监控温度传感器(temperature.py

import random
import time

def read_temperature():
    return random.uniform(20.0, 30.0)

while True:
    temperature = read_temperature()
    print(f"Temperature: {temperature:.2f}°C")

    if temperature >= 28:
        print("Required temperature reached! Stopping monitoring.")
        break

    time.sleep(1)
  • 使用 while True 创建无限循环。
  • 每次读取温度并打印。
  • 当温度 ≥ 28°C 时,break 退出循环。
  • 否则等待 1 秒后继续。

在循环中从可迭代对象中移除元素

在迭代过程中修改集合(尤其是删除元素)是有风险的。但在某些情况下,使用 while 循环是安全的选择。

示例:逐个处理并移除列表元素

>>> colors = ["red", "blue", "yellow", "green"]
>>> while colors:
...     color = colors.pop(-1)
...     print(f"Processing color: {color}")
...
Processing color: green
Processing color: yellow
Processing color: blue
Processing color: red
  • 在布尔上下文中,非空列表为 True,空列表为 False
  • colors.pop(-1) 从末尾移除并返回元素。
  • 当列表为空时,while colors 变为 False,循环终止。

使用 while 循环获取用户输入

从命令行获取用户输入是 while 循环的常见用途。

基础版本(user_input.py

line = input("Type some text: ")

while line != "stop":
    print(line)
    line = input("Type some text: ")

❌ 缺点:input() 被重复调用了两次。

改进版:使用海象运算符(Walrus Operator)

>>> while (line := input("Type some text: ")) != "stop":
...     print(line)
...
Type some text: Python
Python
Type some text: Walrus
Walrus
Type some text: stop
  • 使用 :=(海象运算符)在条件中同时赋值和比较。
  • 代码更简洁,避免重复调用 input()

使用 while 循环遍历迭代器

虽然 for 循环是遍历可迭代对象的首选,但有时你可能需要用 while 循环配合 next() 来更精细地控制迭代过程。

示例:用 while 模拟 for 循环(for_loop.py

requests = ["first request", "second request", "third request"]

print("\nWith a for loop")
for request in requests:
    print(f"Handling {request}")

print("\nWith a while loop")
it = iter(requests)
while True:
    try:
        request = next(it)
    except StopIteration:
        break
    print(f"Handling {request}")

两者输出相同。虽然 for 更简洁,但 while + next() 提供了更多控制权(例如在异常处理或自定义迭代逻辑时)。


模拟 do-while 循环

do-while 循环是一种先执行一次循环体、再判断条件的结构。C/C++/Java/JavaScript 等语言支持它,但 Python 没有原生 do-while 循环

不过,你可以用 while True + break 来模拟:

>>> while True:
...     number = int(input("Enter a positive number: "))
...     print(number)
...     if not number > 0:
...         break
...
Enter a positive number: 1
1
Enter a positive number: 4
4
Enter a positive number: -1
-1
  • 循环体至少执行一次
  • 退出条件放在循环末尾,用 break 终止。

这是 Python 中模拟 do-while 的标准做法。


使用 while 循环实现事件循环

while 循环常用于实现事件循环——一种无限循环,等待特定“事件”发生后分派给相应处理器。

常见应用场景包括:

  • 图形用户界面(GUI)框架
  • 游戏开发
  • 异步应用程序
  • 服务器进程

示例:猜数字游戏(guess.py

from random import randint

LOW, HIGH = 1, 10
secret_number = randint(LOW, HIGH)
clue = ""

while True:
    guess = input(f"Guess a number between {LOW} and {HIGH} {clue} ")
    number = int(guess)
    if number > secret_number:
        clue = f"(less than {number})"
    elif number < secret_number:
        clue = f"(greater than {number})"
    else:
        break

print(f"You guessed it! The secret number is {number}")
  • 游戏循环持续运行,直到用户猜中数字。
  • 每次提供提示(大于或小于)。
  • 猜中时 break 退出循环,显示胜利信息。

探索无限 while 循环

有时你会写出不会自然终止while 循环,这类循环通常称为无限循环(尽管最终总得手动或外部终止)。

无限循环可能是有意为之,也可能是无意错误

无意的无限循环

由于逻辑错误导致循环无法终止。例如:

>>> number = 5
>>> while number != 0:
...     print(number)
...     number -= 2
...
5
3
1
-1
-3
... # 永不停止

解决方案

  1. 修正条件

    >>> while number > 0:
    ...     print(number)
    ...     number -= 2
    ...
    5
    3
    1
    
  2. 添加安全退出机制

    >>> while number != 0:
    ...     if number <= 0:
    ...         break
    ...     print(number)
    ...     number -= 2
    ...
    5
    3
    1
    

关键是要确保循环变量能最终使条件变为假。


有意的无限循环

有意设计的无限循环非常常见且有用,例如:

  • 游戏主循环
  • Web 服务器
  • 后台服务

通常使用 while True,并通过 break 在满足条件时退出:

while True:
    if condition_1:
        break
    ...
    if condition_2:
        break

示例:密码验证(password.py

MAX_ATTEMPTS = 3
correct_password = "secret123"
attempts = 0

while True:
    password = input("Password: ").strip()
    attempts += 1

    if password == correct_password:
        print("Login successful! Welcome!")
        break

    if attempts >= MAX_ATTEMPTS:
        print("Too many failed attempts.")
        break
    else:
        print(f"Incorrect password. {MAX_ATTEMPTS - attempts} attempts left.")
  • 两个退出条件:密码正确 或 尝试次数超限。
  • 使用 break 优雅退出。

总结

你已经深入学习了 Python 的 while 循环——这一关键的控制流结构。你掌握了:

  • while 循环的基本语法与工作原理
  • 如何在条件为真时重复执行任务
  • 如何处理未知迭代次数的场景
  • 使用 breakcontinue 控制循环流程
  • 如何避免无意的无限循环,以及如何正确编写有意的无限循环
  • 模拟 do-while 循环的方法
  • else 子句的使用时机

这些知识使你能够编写动态、灵活的代码,尤其适用于迭代次数未知或依赖条件的场景。

现在,你已经准备好在自己的 Python 项目中高效使用 while 循环了!