《笨办法学 python3》系列练习计划——33.while循环

题目

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

  1. 尽量少用 while 循环,大部分情况下使用 for 循环是更好的选择。
  2. 重复检查你的 while 循环,确定布尔表达式最终会成为 False。
  3. 如果不确定,就在 while 循环的结尾打印要测试的值。看看它的变化。

加分练习

  1. 将这个 while 循环改成一个函数,将测试条件 (i < 6) 中的 6 换成变量。
  2. 使用这个函数重写脚本,并用不同的数字测试。
  3. 为函数添加另一个参数,这个参数用来定义第 8 行的加值 +1 ,这样你就可以让它任意加值了。
  4. 再使用该函数重写一遍这个脚本,看看效果如何。
  5. 接下来使用 for 循环 和 range 把这个脚本再写遍。你还需要中间的加值操作么?如果不去掉会有什么结果?

如果程序停不下来,可是试试按下 ctrl + c 快捷键。




我的答案

33.0 基础练习

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)

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

33.1 - 33.4 用函数重写脚本

第一次修改:

def my_while(loops):
    i = 0
    numbers = []
    while i < loops:
        print("At the top i is %d" % i)
        numbers.append(i)
        i += 1
        print("Numbers now:", numbers)
        print("At the bottom i is %d" % i)
        print("\n---------------")

        print("The numbers:")
        for num in numbers:
            print(num)


my_while(4)

这里写图片描述

第二次修改,增加步长

def my_while(loops, step):
    i = 0
    numbers = []
    while i < loops:
        print("At the top i is %d" % i)
        numbers.append(i)
        i += step
        print("Numbers now:", numbers)
        print("At the bottom i is %d" % i)
        print("\n---------------")

        print("The numbers:")
        for num in numbers:
            print(num)


my_while(7,2)

这里写图片描述

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

numbers = []

for i in range(6):
    print("At the top i is %d" % i)
    numbers.append(i)
    print("Numbers now:", numbers)
    print("At the bottom i is %d" % i)
    print("\n---------------")

print("The numbers:")

for num in numbers:
    print(num)

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




返回目录

《笨办法学 python3》系列练习计划——目录

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章