while-leep 和咱们接触过的 for-loop 相似,它们都会判断一个布尔表达式的真伪。也和 for 循环同样咱们须要注意缩进,后续的练习会偏重这方面的练习。不一样点在于 while 循环在执行完代码后会再次回到 while 所在的位置,再次判断布尔表达式的真伪,并再次执行代码,直到手动关闭 python 或表达式为假。在使用 while 循环时要注意:python
尽可能少用 while 循环,大部分状况下使用 for 循环是更好的选择。
重复检查你的 while 循环,肯定布尔表达式最终会成为 False。
若是不肯定,就在 while 循环的结尾打印要测试的值。看看它的变化。
加分练习
将这个 while 循环改为一个函数,将测试条件 (i < 6) 中的 6 换成变量。
使用这个函数重写脚本,并用不一样的数字测试。
为函数添加另外一个参数,这个参数用来定义第 8 行的加值 +1 ,这样你就可让它任意加值了。
再使用该函数重写一遍这个脚本,看看效果如何。
接下来使用 for 循环 和 range 把这个脚本再写遍。你还须要中间的加值操做么?若是不去掉会有什么结果?
若是程序停不下来,但是试试按下 ctrl + c 快捷键。
app
1 i = 0 2 numbers = [] 3 4 while i < 6: 5 print(f"At the top i is {i}") 6 numbers.append(i) 7 8 i = i + 1 9 print("Numbers now: ", numbers) 10 print(f"At the bottom i is {i}") 11 12 13 print("The numbers: ") 14 15 16 for num in numbers: 17 print(num)
可见,while 循环在未执行完的时候,后面得 for 循环是没法执行的,因此千万肯定 while 循环会结束。函数
第一次修改:oop
1 def my_while(loops): 2 i = 0 3 numbers = [] 4 5 while i < loops: 6 print(f"At the top i is {i}") 7 numbers.append(i) 8 9 i += 1 10 print("Numbers now: ", numbers) 11 print(f"At the bottom i is {i}") 12 13 14 print("The numbers: ") 15 16 for num in numbers: 17 print(num) 18 19 20 my_while(6)
第二次修改,增长步长测试
1 def my_while(loops,step): 2 i = 0 3 numbers = [] 4 5 while i < loops: 6 print(f"At the top i is {i}") 7 numbers.append(i) 8 9 i += step 10 print("Numbers now: ", numbers) 11 print(f"At the bottom i is {i}") 12 13 14 print("The numbers: ") 15 16 for num in numbers: 17 print(num) 18 19 20 my_while(6,2)
1 numbers = [] 2 3 for i in range(6): 4 print(f"At the top i is {i}") 5 numbers.append(i) 6 print("Numbers now: ", numbers) 7 print(f"At the bottom i is {i}") 8 9 print("The numbers: ") 10 11 for num in numbers: 12 print(num)
这里就不须要 i
去加 1 了。
由于在 while 循环中若是没有 i +=1 则布尔式中 i 是不变,i 永远小于 6,这就麻烦了。
但在 for 循环中,循环次数受 range 控制,因此功能上是不须要 i 了。spa