while 循环
while 循环在条件为真时重复执行一段代码。它适合事先不知道需要循环多少次的情况——只要条件满足,就一直执行。
基本语法
count = 0
while count < 5:
print count
count += 1
# 输出:
# 0
# 1
# 2
# 3
# 4
while 后面跟条件,以冒号结尾。缩进块是循环体。每次执行完循环体后,重新检查条件。如果条件仍为真,继续下一次循环;如果为假,退出循环,执行后面的代码。
循环变量
循环变量必须在循环前初始化,在循环体内更新,否则可能形成无限循环:
# 正确:count 在循环中递增
n = 10
while n > 0:
print n
n -= 1
# 错误:n 永远大于 0,无限循环
n = 10
while n > 0:
print n
# 忘记更新 n!
无限循环会耗尽 CPU 资源,需要用 Ctrl+C(发送 KeyboardInterrupt)强制终止。
实际应用
# 计算阶乘
n = 5
result = 1
while n > 1:
result *= n
n -= 1
print result # 120
# 逐位读取数字
num = 1234
while num > 0:
digit = num % 10
print digit
num //= 10
# 输出:4, 3, 2, 1
# 等待用户输入正确值
value = None
while value is None:
user_input = raw_input("Enter a number: ")
if user_input.isdigit():
value = int(user_input)
else:
print "Invalid input, try again."
print "You entered:", value
while-else 子句
Python 的 while 可以带 else 子句,这在其他语言中很少见:
count = 0
while count < 3:
print count
count += 1
else:
print "Loop finished normally"
# 输出:
# 0
# 1
# 2
# Loop finished normally
else 子句在循环正常结束时执行——即条件变为假而退出。如果循环被 break 打断,else 不会执行:
count = 0
while count < 3:
print count
if count == 1:
break
count += 1
else:
print "Loop finished normally" # 不会执行
# 输出:
# 0
# 1
while-else 的用途是区分"循环正常结束"和"被 break 打断"。例如搜索列表中的元素:
items = [1, 3, 5, 7, 9]
target = 6
i = 0
while i < len(items):
if items[i] == target:
print "Found at index", i
break
i += 1
else:
print "Not found" # 如果 break 没触发,执行这里
与 for 循环的选择
| 场景 | 推荐 |
|---|---|
| 遍历已知序列 | for |
| 条件驱动,次数未知 | while |
| 需要索引 | for i in range(...) 或 enumerate |
| 等待外部条件 | while |
# 遍历列表:用 for 更简洁
items = [1, 2, 3, 4, 5]
# while 写法(冗长)
i = 0
while i < len(items):
print items[i]
i += 1
# for 写法(推荐)
for item in items:
print item