Python3练习题系列(03)

时间:2024-05-22 23:32:50

题目:

思考While循环,看看它的特点是什么?

知识点:

while循环

分析:

特点:while-loop(while 循环)。while-loop 会一直执行它下面的代码片段,直到它对应的布尔表达式为False 时才会停下来。

问题:while循环的条件总是为真时,该循环永不停止,直到天荒地老,海枯石烂。

解决:为了避免这样的问题,你需要遵循下面的规定:

1. 尽量少用while-loop,大部分时候for-loop 是更好的选择。
2. 重复检查你的while 语句,确定你测试的布尔表达式最终会变成False 。
3. 如果不确定,就在while-loop 的结尾打印出你要测试的值。看看它的变化。

代码分析:

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, end='\t')

结果:

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 来自《笨办法学Python》