On this page

Python While 循环语句

Python While 循环语句详解

while 循环是 Python 中用于重复执行代码块的基本循环结构之一。它会在条件为真时持续执行循环体,直到条件变为假为止。

基本语法

while 条件表达式:
    # 循环体代码块
    # 需要改变条件变量的值,避免无限循环

简单示例

count = 0
while count < 5:
    print(f"当前计数: {count}")
    count += 1  # 这行很重要,避免无限循环

输出:

当前计数: 0
当前计数: 1
当前计数: 2
当前计数: 3
当前计数: 4

关键特点

  1. 条件检查:每次循环开始前检查条件
  2. 循环体:缩进的代码块会被重复执行
  3. 条件更新:必须在循环体内更新条件变量

常见应用场景

1. 计数器循环

# 打印1-10的平方
num = 1
while num <= 10:
    print(f"{num}的平方是{num**2}")
    num += 1

2. 用户输入验证

password = ""
while password != "secret":
    password = input("请输入密码: ")
print("密码正确,欢迎进入!")

3. 处理列表/可迭代对象

fruits = ["苹果", "香蕉", "橙子"]
while fruits:  # 当列表不为空时
    print(f"吃掉一个{fruits.pop()}")
print("水果吃完了!")

循环控制语句

1. break - 立即退出循环

while True:  # 看似无限循环
    answer = input("输入quit退出: ")
    if answer.lower() == "quit":
        break  # 跳出循环
    print(f"你输入了: {answer}")

2. continue - 跳过当前迭代

num = 0
while num < 10:
    num += 1
    if num % 2 == 0:  # 跳过偶数
        continue
    print(f"奇数: {num}")

3. else 子句 - 循环正常结束时执行

count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("循环正常结束")  # 没有被break中断时执行

避免无限循环

忘记更新条件变量会导致无限循环:

# 错误示例 - 无限循环
x = 1
while x < 5:
    print(x)
    # 忘记写 x += 1

解决方案:

  1. 确保循环条件最终会变为False
  2. 使用break提供退出机制
  3. 设置最大迭代次数作为保险

实际应用示例

1. 猜数字游戏

import random

target = random.randint(1, 100)
guess = None
attempts = 0

while guess != target:
    guess = int(input("猜一个1-100的数字: "))
    attempts += 1
    
    if guess < target:
        print("猜小了!")
    elif guess > target:
        print("猜大了!")

print(f"恭喜!你用了{attempts}次猜中了数字{target}")

2. 菜单系统

while True:
    print("\n菜单:")
    print("1. 查看余额")
    print("2. 存款")
    print("3. 取款")
    print("4. 退出")
    
    choice = input("请选择操作(1-4): ")
    
    if choice == "1":
        print("余额查询功能")
    elif choice == "2":
        print("存款功能")
    elif choice == "3":
        print("取款功能")
    elif choice == "4":
        print("感谢使用,再见!")
        break
    else:
        print("无效输入,请重新选择")

while vs for 循环

特性while 循环for 循环
适用场景条件不确定的循环遍历已知序列
循环次数由条件决定由序列长度决定
初始化需要在循环外初始化变量自动处理迭代变量
典型用例用户输入验证、游戏循环遍历列表、固定次数循环

性能注意事项

  1. 避免在循环体内进行不必要的计算
  2. 对于大数据集,考虑使用生成器表达式
  3. 复杂的条件判断可能会影响性能

总结

  • while 循环适合条件不确定的重复操作
  • 必须确保循环条件最终会变为False
  • 使用breakcontinue可以更灵活地控制循环
  • else子句在循环正常结束时执行
  • 避免无限循环是关键

掌握while循环可以让你处理更复杂的控制流程,特别是在需要根据运行时条件决定循环次数的情况下。