while循环会经常出现无法结束的情况,为避免类似问题,需遵循以下规定:
- 优先使用for循环,而不是while循环
- 重复检查while语句,确定测试的布尔表达式最终会变成False
- 若不确定,就在while循环结尾打印出要测试的值,监视其变化。
i = 0
numbers = []
while i < 6:
print("At the top i is %d" % i)
numbers.append(i)
i += 1
print("Numbers now: ",numbers)
print("At the bottom i is %d" % i)
print("The numbers:")
for num in numbers:
print(num)
for循环只能对一些东西的集合进行循环,while循环可以对任何对象进行驯化。