標籤:程式 提示 print ice 停止 測試結果 rem person 提取
使用while迴圈
你可以使用while迴圈來數數。
current_number = 1while current_number <= 5: print(current_number) current_number += 1
讓使用者選擇何時退出
可使用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) print(message)
我們建立一個變數——message,用於儲存使用者輸入的值。我們將變數message的初始值設定為空白字串””,讓python首次執行while代碼時有可供檢查的東西。python首次執行while語句時,需要將message的值與’quit’進行比較,但此時使用者還沒有輸入。如果沒有可供比較的東西,python將無法繼續運行程式。為解決這個問題,我們必須給message指定一個初始值。雖然這個初始值只是一個Null 字元串。
Tell me something,and I will repeat it back to you: Enter ‘quit‘ to end the program.Hello everyone!Hello everyone!Tell me something,and I will repeat it back to you: Enter ‘quit‘ to end the program.Hello again!Hello again!Tell me something,and I will repeat it back to you: Enter ‘quit‘ to end the program.quitquit
如果不想將單詞’quit’列印出來,只需要一個簡單的if測試。
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)
程式在顯示訊息前將做簡單的檢查,僅在訊息不是退出值時才列印它。
使用標誌
在前一個樣本,我們讓程式在滿足指定條件時就執行特定的任務。但在更複雜的程式中,很多不同的事件會導致程式停止運行,如果在一條while語句中檢查所有的事件將複雜而困難。
在要求很多條件都滿足才繼續啟動並執行程式中,可定義一個變數,用於判斷整個程式是否處於活躍狀態。這個變數被稱為標誌。
你可以讓程式在標誌為True時繼續運行,並在任何事件導致標誌的值為False時讓程式停止。這樣while語句中就只需檢查一個條件——標誌的真假。從而讓程式便簡潔。
prompt = "\nTell me something,and I will repeat it back to you: "prompt += "\nEnter ‘quit‘ to end the program."active = Truewhile active: message = input(prompt) if message == ‘quit‘: active = False else: print(message)
我們將變數active設定成立True,讓程式處在活躍狀態。這樣做簡化了while語句。
使用break退出迴圈
要立即退出while迴圈,不再運行迴圈中的代碼,可使用break語句。break語句用於控製程序流程,可使用它控制哪些代碼執行,哪些不執行。
例如,來看一個讓使用者指出他到過哪些地方的程式。在這個程式中,我們可以在使用者輸入’quit’後使用break語句立刻退出while迴圈:
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() + "!")在迴圈中使用continue
要返回到迴圈開頭,並根據條件測試結果決定是繼續執行迴圈,可使用continue語句。
例如,來看一個從1數到10,但只列印其中奇數的迴圈。
current_number = 0while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number)
避免無限迴圈
每個while迴圈都必須有停止啟動並執行途徑,這樣才不會沒完沒了地執行下去。
使用while迴圈來處理列表和字典
for迴圈是一種遍曆列表的有效方式,但在for迴圈中不應該修改列表,否則將導致python難以跟蹤其中的元素。要在遍曆列表的同時對其進行修改,可使用while迴圈。通過將while迴圈同列表和字典結合起來使用,可收集,儲存並組織大量輸入,供以後查看和顯示。
在列表之間移動元素
假設有一個列表,其中包含新註冊但還未收到驗證的網站使用者;驗證這些使用者後,如何將他們移動到另一個已驗證使用者列表中呢?一種辦法是使用while迴圈,在驗證使用者的同時將其從未驗證使用者列表中提取出來,再將其加入到另一個已經驗證使用者列表中。
#首先,建立一個帶驗證使用者列表和一個使用者儲存已驗證使用者的空列表。unconfirmed_users = [‘alice‘,‘brain‘,‘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())
我們首先建立了一個未驗證使用者列表,還建立一個空列表,用於存放已驗證使用者。while迴圈不斷運行,直到列表unconfirmed_users變為空白。在這個迴圈中函數pop()以每次一個的方式從列表unconfirmed_users末尾刪除未驗證的使用者。
Verifying user: CandaceVerifying user: BrainVerifying user: AliceThe following users have been confirmed:CandaceBrainAlice
刪除包含特定值的所有列表元素
假設你有一個寵物列表,其中包含多個值為’cat’的元素,要刪除所有這些元素,可不斷運行一個while迴圈。
pets = ["dog","cat","dog","goldfish","cat","rabbit","cat"]print(pets)while "cat" in pets: pets.remove("cat")print(pets)
[‘dog‘, ‘cat‘, ‘dog‘, ‘goldfish‘, ‘cat‘, ‘rabbit‘, ‘cat‘][‘dog‘, ‘dog‘, ‘goldfish‘, ‘rabbit‘]
使用使用者輸入填充字典
可使用while迴圈提示使用者輸入任意數量的資訊。下面來建立一個調查程式,其中的迴圈每次執行時都提示輸入被調查者的名字和回答。我們將收集的資料存在一個字典中,以便將回答同被調查者關聯起來。
responses = {}#設定一個標誌,指出調查是否繼續polling_active = Truewhile polling_active: #提示輸入被調查者的名字和回答 name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb sunday? ") #將答案儲存在字典中 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 + ".")
python隨筆7(while迴圈)