while 循环
while 循环让程序能够在条件满足时反复执行一段代码。与 for 循环遍历已知序列不同,while 更适合"事先不知道要循环多少次"的场景——只要某个条件保持为真,循环就持续运转。
基本语法
while 语句以关键字 while 开头,后跟条件表达式和冒号,缩进的代码块构成循环体:
count = 0
while count < 5:
print(count)
count += 1
程序先判断 count < 5,初始为真,进入循环体打印 0,然后将 count 增加到 1。每次迭代结束后,Python 回到 while 重新判断条件。当 count 变为 5 时,条件为假,循环终止,程序继续执行循环之后的代码。最终输出 0 到 4。
终止条件
while 循环必须有明确的终止条件,否则条件永远为真,循环将无限执行下去。终止条件通常依赖循环体内被修改的变量:
# 用户输入验证
password = ""
while password != "secret":
password = input("请输入密码:")
print("验证通过")
上面的循环持续要求用户输入,直到输入正确密码为止。循环变量 password 在每次迭代中被重新赋值,最终可能满足退出条件。
另一种终止方式是循环体内根据业务逻辑决定是否继续:
balance = 1000
withdrawal_count = 0
while balance > 0:
amount = int(input(f"余额 {balance},请输入取款金额(0 退出):"))
if amount == 0:
break # 用户主动退出
if amount > balance:
print("余额不足")
continue
balance -= amount
withdrawal_count += 1
print(f"共取款 {withdrawal_count} 次,剩余 {balance}")
死循环
如果 while 的条件永远为真,且循环体内没有 break、return 或异常来中断,程序将陷入死循环:
# 死循环示例
while True:
print("正在运行...")
上面的代码会无限打印,直到用户强制终止程序(如按 Ctrl+C 触发 KeyboardInterrupt)。死循环并非总是错误,某些场景下它是设计意图:
# 服务器事件循环
while True:
connection = accept_connection()
if connection is None:
continue
handle_request(connection)
长期运行的服务程序、游戏主循环、嵌入式设备的轮询逻辑,都依赖 while True 配合内部的中断机制来持续工作。
while-else 结构
while 循环可以带一个 else 子句,它在循环条件变为假值后执行。关键特性是:如果循环被 break 提前终止,else 不会执行:
count = 3
while count > 0:
print(f"倒计时:{count}")
count -= 1
else:
print("发射!")
正常结束时输出:
倒计时:3
倒计时:2
倒计时:1
发射!
如果加入 break:
count = 3
while count > 0:
print(f"倒计时:{count}")
if count == 2:
print("紧急中止")
break
count -= 1
else:
print("发射!") # 不会执行
while-else 的语义将在《循环的 else 子句》文档中深入讨论。
循环变量的更新
忘记在循环体内更新条件变量是最常见的 while 循环错误:
# 错误:i 永远为 0,死循环
i = 0
while i < 5:
print(i)
# 忘记写 i += 1
更新操作的位置也很重要。如果放在 continue 之后,可能导致某些分支跳过更新:
i = 0
while i < 5:
if i == 2:
i += 1 # 必须在 continue 之前更新
continue
print(i)
i += 1
与 for 循环的选择
while 和 for 各有适用场景:
for适合:遍历已知序列、固定次数的重复、迭代字典/字符串等while适合:等待外部条件(用户输入、网络响应)、不确定次数的尝试、条件驱动的持续处理
# while 更适合:不确定次数
import random
target = random.randint(1, 100)
guess = 0
attempts = 0
while guess != target:
guess = int(input("猜一个 1-100 的数字:"))
attempts += 1
if guess < target:
print("太小了")
elif guess > target:
print("太大了")
print(f"恭喜!用了 {attempts} 次猜中")
边界情况
零次迭代:如果 while 的初始条件即为假,循环体一次都不会执行:
x = 10
while x < 5:
print("这行不会输出")
x += 1
浮点数比较陷阱:用浮点数作为循环条件时,精度误差可能导致意外行为:
# 危险:浮点数累加可能永远无法精确等于 1.0
x = 0.0
while x != 1.0:
x += 0.1
print(x)
if x > 2.0:
break # 防止死循环
更安全的做法是用整数计数或容差比较:
for i in range(11): # 0 到 10
x = i * 0.1
print(x)
while 循环是处理条件驱动型重复任务的核心工具,正确使用它需要时刻关注终止条件的可达性和循环变量的更新逻辑。