《笨方法学Python》加分题33

while-leep 和我们接触过的 for-loop 类似,它们都会判断一个布尔表达式的真伪。也和 for 循环一样我们需要注意缩进,后续的练习会偏重这方面的练习。不同点在于 while 循环在执行完代码后会再次回到 while 所在的位置,再次判断布尔表达式的真伪,并再次执行代码,直到手动关闭 python 或表达式为假。在使用 while 循环时要注意:

尽量少用 while 循环,大部分情况下使用 for 循环是更好的选择。
重复检查你的 while 循环,确定布尔表达式最终会成为 False。
如果不确定,就在 while 循环的结尾打印要测试的值。看看它的变化。
加分练习
将这个 while 循环改成一个函数,将测试条件 (i < 6) 中的 6 换成变量。
使用这个函数重写脚本,并用不同的数字测试。
为函数添加另一个参数,这个参数用来定义第 8 行的加值 +1 ,这样你就可以让它任意加值了。
再使用该函数重写一遍这个脚本,看看效果如何。
接下来使用 for 循环 和 range 把这个脚本再写遍。你还需要中间的加值操作么?如果不去掉会有什么结果?
如果程序停不下来,可是试试按下 ctrl + c 快捷键。

33.0 基础练习

 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 循环会结束。

33.1 - 33.4 用函数重写脚本

第一次修改:

 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)

33.5 使用 for 循环和 range 重写代码

 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 了。

猜你喜欢

转载自www.cnblogs.com/python2webdata/p/10416023.html