《笨方法学Python》加分题33

时间:2023-03-08 15:28:42
《笨方法学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 基础练习

 i = 0
numbers = [] while i < 6:
print(f"At the top i is {i}")
numbers.append(i) i = i + 1
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers:
print(num)

《笨方法学Python》加分题33

可见,while 循环在未执行完的时候,后面得 for 循环是无法执行的,所以千万确定 while 循环会结束。

33.1 - 33.4 用函数重写脚本

第一次修改:

 def my_while(loops):
i = 0
numbers = [] while i < loops:
print(f"At the top i is {i}")
numbers.append(i) i += 1
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers:
print(num) my_while(6)

《笨方法学Python》加分题33

第二次修改,增加步长

 def my_while(loops,step):
i = 0
numbers = [] while i < loops:
print(f"At the top i is {i}")
numbers.append(i) i += step
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers:
print(num) my_while(6,2)

《笨方法学Python》加分题33

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

 numbers = []

 for i in range(6):
print(f"At the top i is {i}")
numbers.append(i)
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers:
print(num)

《笨方法学Python》加分题33

这里就不需要 i 去加 1 了。 
因为在 while 循环中如果没有 i +=1 则布尔式中 i 是不变,i 永远小于 6,这就麻烦了。 
但在 for 循环中,循环次数受 range 控制,所以功能上是不需要 i 了。