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