本片博文將介紹input()函數和while循環的使用app
函數input() 讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入後,Python將其存儲在一個變量中,以方便你使用。ide
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 循環不斷地運行,直到指定的條件不知足爲止ui
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,循環將中止,整個程序也將到此結束spa
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 循環讓程序在用戶願意時不斷地運行,咱們在其中定義了一個退出值,只要用戶輸入的不是這個值,程序就接着運行code
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 的事件)都放在其餘地方,從而讓程序變得更爲整潔。blog
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將這個數字打印出來
for 循環是一種遍歷列表的有效方式,但在for 循環中不該修改列表,不然將致使Python難以跟蹤其中的元素。要在遍歷列表的同時對其進行修改,可以使用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())
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
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 + ".")