题目:
思考While循环,看看它的特点是什么?
知识点:
while循环
分析:
特点:while-loop(while 循环)。while-loop 会一直执行它下面的代码片段,直到它对应的布尔表达式为False 时才会停下来。
问题:while循环的条件总是为真时,该循环永不停止,直到天荒地老,海枯石烂。
解决:为了避免这样的问题,你需要遵循下面的规定:
1. 尽量少用while-loop,大部分时候for-loop 是更好的选择。
2. 重复检查你的while 语句,确定你测试的布尔表达式最终会变成False 。3. 如果不确定,就在while-loop 的结尾打印出你要测试的值。看看它的变化。代码分析:
i = 0numbers = []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 0Numbers now: [0]At the bottom i is 1At the top i is 1Numbers now: [0, 1]At the bottom i is 2At the top i is 2Numbers now: [0, 1, 2]At the bottom i is 3At the top i is 3Numbers now: [0, 1, 2, 3]At the bottom i is 4At the top i is 4Numbers now: [0, 1, 2, 3, 4]At the bottom i is 5At the top i is 5Numbers now: [0, 1, 2, 3, 4, 5]At the bottom i is 6The numbers: 0 1 2 3 4 5 来自《笨办法学Python》