用while寫倒三角_練習 33 - while 迴圈 - Learn Python 3 The Hard Way
技術標籤:用while寫倒三角
練習 33 While 迴圈
現在我們來看一個新的迴圈: while-loop。只要一個布林表示式是 True,while-loop 就會一直執行它下面的程式碼塊。
等等,你應該能理解這些術語吧?如果我們寫一行以 : 結尾的程式碼,它就會告訴 Python 開始一個新的程式碼塊。我們用這種方式來結構化你的程式,以便 Python 明白你的意圖。如果你還沒有掌握這塊內容,先回去複習一下,再做一些 if 語句、函式以及 for-loop,直到你掌握為止。
之後我們會做一些練習來訓練你的大腦讀取這些結構,就像我們訓練你掌握布林表示式一樣。
回到 while-loop,它所做的只是像 if 語句一樣的測試,但是它不是隻執行一次程式碼塊,而是在 while 是對的地方回到頂部再重複,直到表示式為 False。
但是 while-loop 有個問題:有時候它們停不下來。如果你的目的是讓程式一直執行直到宇宙的終結,那這樣的確很屌。但大多數情況下,你肯定是需要你的迴圈最終能停下來的。
為了避免這些問題,你得遵守一些規則:
1、保守使用 while-loop,通常用 for-loop 更好一些。
2、檢查一下你的 while 語句,確保布林測試最終會在某個點結果為 False。
3、當遇到問題的時候,把你的 while-loop 開頭和結尾的測試變數打印出來,看看它們在做什麼。
在這個練習中,你要通過以下三個檢查來學習 while-loop:
ex33.py
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 for num in numbers: 16 print(num)
你會看到
練習 33 會話
$ python3.6 ex33.py At the top i is 0 Numbers now: [0] At the bottom i is 1 At the top i is 1 Numbers now: [0, 1] At the bottom i is 2 At the top i is 2 Numbers now: [0, 1, 2] At the bottom i is 3 At the top i is 3 Numbers now: [0, 1, 2, 3] At the bottom i is 4 At the top i is 4 Numbers now: [0, 1, 2, 3, 4] At the bottom i is 5 At the top i is 5 Numbers now: [0, 1, 2, 3, 4, 5] At the bottom i is 6 The numbers: 0 1 2 3 4 5
附加練習
1、把這個 while-loop 轉換成一個你可以呼叫的函式,然後用一個變數替代 i < 6 裡面的 6。
2、用這個函式重新寫一下這個指令碼,試試不同的數值。
3、再增加一個變數給這個函式的引數,然後改變第 8 行的 +1,讓它增加的值與之前不同。
4、用這個函式重新寫這個指令碼,看看會產生什麼樣的效果。
5、用 for-loop 和 range 寫這個指令碼。你還需要中間的增加值嗎?如果不去掉這個增加值會發生什麼?
任何時候你在執行程式的時候它失控了,只用按下 CTRL-C
,程式就會終止。
常見問題
for-loop 和 while-loop 的區別是什麼? for-loop 只能迭代(迴圈)一些東西的集合,而 while-loop 能夠迭代(迴圈)任何型別的東西。不過,while-loop 很難用對,而你通常能夠用 for-loop 完成很多事情。
迴圈好難,我應該如何理解它們?人們不理解迴圈的主要原因是他們跟不上程式碼的執行。當一個迴圈執行的時候,它會過一遍程式碼塊,到結尾之後再跳到頂部。為了直觀表現這個過程,你可以用 print 打印出迴圈的整個過程,把 print 行寫在迴圈的前面、頂部、中間、結尾。研究一下輸出的內容,試著理解它是如何執行的。