《笨辦法學 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》系列練習計劃——目錄

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