while-loop``(while 循环)。``while-loop 会一直执行它下面的代码片段,直到它对应的布尔表达式为 False 时才会停下来。
回到 while 循环,它所作的和 if 语句类似,也是去检查一个布尔表达式的真假,不一样的是它下面的代码片段不是只被执行一次,而是执行完后再调回到 while 所在的位置,如此重复进行,直到 while 表达式为 False 为止。
While 循环有一个问题,那就是有时它会永不结束。如果你的目的是循环到宇宙毁灭为止,那这样也挺好的,不过其他的情况下你的循环总需要有一个结束点。为了避免这样的问题,你需要遵循下面的规定:
1. 尽量少用 while-loop,大部分时候 for-loop 是更好的选择。
2. 重复检查你的 while 语句,确定你测试的布尔表达式最终会变成 False 。
3. 如果不确定,就在 while-loop 的结尾打印出你要测试的值。看看它的变化。
在这节练习中,你将通过上面的三样事情学会 while-loop :
i = 0
numbers = []
while i < 6: # 判断i是否小于6
print("At the top i is %d" % i) # d打印现在计算的i
numbers.append(i) # 向numbers序列添加i
i += 1 # i+1后赋值给i
print("Number now: ", numbers) # 打印赋值后的numbers序列
print("At the bottom i is %d" % i) # 打印新加入的数字吧
print ("The numbers:") # 打印while循环结束后的序列
for num in numbers: # for循环打印number序列中的数字
print(num)
结果
# python ex33.py
At the top i is 0
Number now: [0]
At the bottom i is 1
At the top i is 1
Number now: [0, 1]
At the bottom i is 2
At the top i is 2
Number now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
Number now: [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Number now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Number now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5
num = []
for i in range(0,6):
num.append(i)
print(num)
结果
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
i = int(input("请输入1-6内任意一个整数 \n"))
if i == 1:
num = [0]
for i in range(i,6):
num.append(i)
i += 1
print(num)
elif i == 2:
num = [0,1]
for i in range(i, 6):
num.append(i)
i += 1
print(num)
elif i == 3:
num = [0,1,2]
for i in range(i, 6):
num.append(i)
i += 1
print(num)
elif i == 4:
num = [0,1,2,3]
for i in range(i, 6):
num.append(i)
i += 1
print(num)
elif i == 5:
num = [0,1,2,3,4]
for i in range(i, 6):
num.append(i)
i += 1
print(num)
else:
num = [0,1,2,3,4,5]
print(num)
结果
请输入1-6内任意一个整数
1
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
请输入1-6内任意一个整数
4
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]