1. 程式人生 > >Python基礎之While迴圈

Python基礎之While迴圈

一、摘要

本片博文將介紹input()函式和while迴圈的使用

二、input()函式

函式input() 讓程式暫停執行,等待使用者輸入一些文字。獲取使用者輸入後,Python將其儲存在一個變數中,以方便你使用。

message = input("Tell me something, and I will repeat it back to you: ")
print(message)

函式input() 接受一個引數:即要向用戶顯示的提示 或說明,讓使用者知道該如何做。在這個示例中,Python執行第1行程式碼時,使用者將看到提示Tell me something, and I will repeat it back to you: 程式等待使用者輸入,並在使用者按回車鍵後繼續執行。輸入儲存在變數message 中,接下來的print(message) 將輸入呈現給使用者,有時候,提示可能超過一行,例如,你可能需要指出獲取特定輸入的原因。在這種情況下,可將提示儲存在一個變數中,再將該變數傳遞給函式input() 。這樣,即便提示超過一行,input() 語句也非常清晰。

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")

使用函式input() 時,Python將使用者輸入解讀為字串。請看下面讓使用者輸入其年齡的直譯器會話:

>>> age = input("How old are you? ")
How old are you? 21
>>> age '21'

使用者輸入的是數字21,但我們請求Python提供變數age 的值時,它返回的是'21' ——使用者輸入的數值的字串表示,是個字串自然就不能當作數字來使用,否則會報TypeError,我們如果要當作數字來使用,就需要使用int()函式來轉換

>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True
height = input("How tall are you, in inches? 
") height = int(height) if height >= 36:   print("\nYou're tall enough to ride!") else:   print("\nYou'll be able to ride when you're a little older.")
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
  print("\nThe number " + str(number) + " is even.")
else:
  print("\nThe number " + str(number) + " is odd.")

三、while迴圈

while 迴圈不斷地執行,直到指定的條件不滿足為止

current_number = 1
while current_number <= 5:
  print(current_number)
  current_number += 1

只要current_number 小於或等於5,就接著執行這個迴圈。迴圈中的程式碼列印current_number 的值,再使用程式碼current_number += 1 (程式碼current_number = current_number + 1 的簡寫)將其值加1。只要滿足條件current_number <= 5 ,Python就接著執行這個迴圈。由於1小於5,因此Python列印1 ,並將current_number 加1,使其為2 ;由於2小於5,因此Python列印2 ,並將current_number 加1 ,使其為3 ,以此類推。一旦current_number 大於5,迴圈將停止,整個程式也將到此結束

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
  message = input(prompt)
  print(message)

可使用while 迴圈讓程式在使用者願意時不斷地執行,我們在其中定義了一個退出值,只要使用者輸入的不是這個值,程式就接著執行

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
  message = input(prompt)
  if message != 'quit':
    print(message)

在要求很多條件都滿足才繼續執行的程式中,可定義一個變數,用於判斷整個程式是否處於活動狀態。這個變數被稱為標誌 ,充當了程式的交通訊號燈。你可讓程式在標誌為True 時繼續執行,並在任何事件導致標誌的值為False 時讓程式停止執行。這樣,在while 語句中就只需檢查一個條件——標誌的當前值是否為True ,並將所有測試(是否發生了應將標誌設定為False 的事件)都放在其他地方,從而讓程式變得更為整潔。

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True # 標誌
while active:
  message = input(prompt)
  if message == 'quit':
    active = False
  else:
    print(message)

要立即退出while 迴圈,不再執行迴圈中餘下的程式碼,也不管條件測試的結果如何,可使用break 語句。break 語句用於控制程式流程,可使用它來控制哪些程式碼行將執行,哪些程式碼行不執行,從而讓程式按你的要求執行你要執行的程式碼。

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
  city = input(prompt)
  if city == 'quit':
    break
  else:
    print("I'd love to go to " + city.title() + "!")

注意:在任何Python迴圈中都可使用break 語句。例如,可使用break 語句來退出遍歷列表或字典的for 迴圈。

要返回到迴圈開頭,並根據條件測試結果決定是否繼續執行迴圈,可使用continue 語句,它不像break 語句那樣不再執行餘下的程式碼並退出整個迴圈。

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

if 語句檢查current_number 與2的求模運算結果。如果結果為0(意味著current_number 可被2整除),就執行continue 語句,讓Python忽略餘下的程式碼,並返回到迴圈的開頭。如果當前的數字不能被2整除,就執行迴圈中餘下的程式碼,Python將這個數字打印出來

四、使用while 迴圈來處理列表和字典

for 迴圈是一種遍歷列表的有效方式,但在for 迴圈中不應修改列表,否則將導致Python難以跟蹤其中的元素。要在遍歷列表的同時對其進行修改,可使用while 迴圈。通過將while 迴圈同列表和字典結合起來使用,可收集、儲存並組織大量輸入,供以後檢視和顯示

  • 在列表之間移動元素:假設有一個列表,其中包含新註冊但還未驗證的網站使用者;驗證這些使用者後,如何將他們移到另一個已驗證使用者列表中呢?一種辦法是使用一個while 迴圈,在驗證使用者的同時將其從未驗證使用者列表中提取出來,再將其加入到另一個已驗證使用者列表中。程式碼可能類似於下面這樣:
# 首先,建立一個待驗證使用者列表
# 和一個用於儲存已驗證使用者的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 驗證每個使用者,直到沒有未驗證使用者為止
# 將每個經過驗證的列表都移到已驗證使用者列表中
while unconfirmed_users:
  current_user = unconfirmed_users.pop()
  print("Verifying user: " + current_user.title())
  confirmed_users.append(current_user)
# 顯示所有已驗證的使用者
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
  print(confirmed_user.title())
  • 刪除包含特定值的所有列表元素:我們可以使用函式remove() 來刪除列表中的特定值,但每次只能刪除一個,如果要刪除列表中所有包含特定值的元素,該怎麼辦呢?假設你有一個寵物列表,其中包含多個值為'cat' 的元素。要刪除所有這些元素,可不斷執行一個while 迴圈,直到列表中不再包含值'cat' ,如下所示:
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
  pets.remove('cat')
print(pets)
  • 使用使用者輸入來填充字典:可使用while迴圈提示使用者輸入任意數量的資訊。下面來建立一個調查程式,其中的迴圈每次執行時都提示輸入被調查者的名字和回答。我們將收集的資料儲存在一個字典中,以便將回答同被調查者關聯起來:
responses = {}
# 設定一個標誌,指出調查是否繼續
polling_active = True
while polling_active:
# 提示輸入被調查者的名字和回答
  name = input("\nWhat is your name? ")
  response = input("Which mountain would you like to climb someday? ")
  # 將答卷儲存在字典中
  responses[name] = response
  # 看看是否還有人要參與調查
  repeat = input("Would you like to let another person respond? (yes/ no) ")
  if repeat == 'no':
    polling_active = False
# 調查結束,顯示結果
print("\n--- Poll Results ---")
for name, response in responses.items():
  print(name + " would like to climb " + response + ".")