零基礎快樂學Python(11)——while迴圈

這一節我們主要來介紹while迴圈。

之前的for迴圈是將元素從頭到尾遍歷一遍,而while迴圈是一直執行,直到碰到不符合的條件的情況。

來看個小例子:

number = 0while number <= 3: print(number) number += 1

我們先將變數

number

設為0,然後在while迴圈中,只要變數小於等於3,這個迴圈將一直執行下去。迴圈體的最後一行是

number

+=

1

,這是number=number+1的簡寫。這行程式碼的作用是,可以讓變數

number

不斷增加1,最後超過3,破壞while迴圈中的條件。否則程式碼就會一直執行下去。

我們可以利用while的這個特性,讓使用者在輸入資訊時可以選擇隨時終止。比如下面這個例子:

info = “Let‘s play a game。Enter a informatin,then you get a same one: \n”info += “Enter ’quit‘ to end this game。”i = ’‘while i != ’quit‘: i = input(info) print(i)

首先,我們指定了一些提示資訊,儲存在變數info中。然後指定了一個空字串,為了讓while迴圈能夠開始。隨後將使用者輸入的資訊儲存在變數i中,只要使用者輸入的不是‘quit’,那麼迴圈將一直進行下去。

比如,我們先輸入‘james’,然後輸入‘quit’,來看下結果:

Let’s play a game。Enter a informatin,then you get a same one: Enter ‘quit’ to end this game。jamesjamesLet‘s play a game。Enter a informatin,then you get a same one: Enter ’quit‘ to end this game。quitquit

上面的程式碼最後有個小缺陷,就是當我們輸入‘quit’後,還是會將其打印出來。為了不列印這個‘quit’,我們可以在while迴圈中新增一個if語句:

info = “Let’s play a game。Enter a informatin,then you get a same one: \n”info += “Enter ‘quit’ to end this game。”i = ‘’while i != ‘quit’: i = input(info) if i != ‘quit’: print(i)

關鍵在於第6行程式碼,只有在變數i不為‘quit’時,我們才將其列印。來看下輸出結果:

Let‘s play a game。Enter a informatin,then you get a same one: Enter ’quit‘ to end this game。anthonyanthonyLet’s play a game。Enter a informatin,then you get a same one:Enter ‘quit’ to end this game。quit

此外,我們還可以設定一個標籤,讓while後的表示式更簡潔:

info = “Let‘s play a game。Enter a informatin,then you get a same one: \n”info += “Enter ’quit‘ to end this game。”flag = Truewhile flag: i = input(info) if i == ’quit‘: flag = False else: print(i)

第3行程式碼中,我們設定了一個變數flag,令其為True。只要flag的值為True,while迴圈就將一直執行下去。在迴圈體中,我們設定了一個if語句,當用戶輸入‘quit’時,flag的值將為False,從而使while迴圈終止。

我們輸入‘wade’和‘quit’,來看下結果:

Let’s play a game。Enter a informatin,then you get a same one: Enter ‘quit’ to end this game。wadewadeLet‘s play a game。Enter a informatin,then you get a same one: Enter ’quit‘ to end this game。quit

另外,還可以使用關鍵字break,立刻跳出while迴圈。因此,上述程式碼可更改為:

info = “Let’s play a game。Enter a informatin,then you get a same one: \n”info += “Enter ‘quit’ to end this game。”while True: i = input(info) if i == ‘quit’: break else: print(i)

while

True

表示迴圈將一直執行下去,除非使用者輸入‘quit’,此時將執行break語句,立刻終止while迴圈。

如果你只是想跳過迴圈體中的某些語句而不是終止迴圈,那麼可以使用continue語句:

number = 0while number <= 10: number += 1 if number % 2 != 0: continue print(number)

上面的程式碼可以讓我們列印0-10中的偶數,注意到第4、第5行程式碼中,如果變數

number

的餘數不為0,透過continue語句,我們將直接執行下一次迴圈,而跳過隨後的print語句。這樣就打達到了只打印偶數,不列印奇數的目的。

今天的內容有點多,不過還是很好理解的,加油!快樂繼續中!