又一个循环语句,关键字while。while会检测跟在其后的条件表达式真假,如果为真,就会一直循环下去。使用while注意两点:
- 尽量使用for
- 确保条件最终会判为假,不然一直循环下去直到天地毁灭,俗称死循环
上代码,ex33.py:
#!/usr/bin/python
# -*- coding: utf-8 -*-
i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
运行结果:
At the top i is 0
Numbers now: [0]
At the bottom i is 1
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5