用戶輸入和while循環(huán)
用戶輸入input
函數(shù)input()讓程序暫停運(yùn)行,等待用戶輸入一些文本。獲取用戶輸入后,Python將其存儲(chǔ)在 一個(gè)變量中,以方便你使用。函數(shù)input()接受一個(gè)參數(shù):即要向用戶顯示的提示或說明,讓用戶知道該如何做。
一個(gè)示例:
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
有時(shí)候,提示可能超過一行,例如,你可能需要指出獲取特定輸入的原因。在這種情況下, 可將提示存儲(chǔ)在一個(gè)變量中,再將該變量傳遞給函數(shù)input()。這樣,即便提示超過一行,input() 語(yǔ)句也非常清晰。
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 + "!")
使用函數(shù)input()時(shí),python將用戶輸入解讀為字符串!如果需要int型的數(shù)值,需要通過int()來轉(zhuǎn)換:
age = input("How old are you?")
print(type(age))
age = int(age)
print(type(age))
while循環(huán)
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
while后跟循環(huán)的控制條件,滿足條件時(shí)循環(huán)進(jìn)行,不滿足條件時(shí)退出循環(huán)。
另一個(gè)例子:
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)
首次遇到這個(gè)循環(huán)時(shí),message是一個(gè)空字符串,因此Python進(jìn)入這個(gè)循環(huán)。執(zhí)行到代碼行 message = input(prompt)時(shí),Python顯示提示消息,并等待用戶輸入。不管用戶輸入是什么,都 將存儲(chǔ)到變量message中并打印出來;接下來,Python重新檢查while語(yǔ)句中的條件。只要用戶輸 入的不是單詞'quit',Python就會(huì)再次顯示提示消息并等待用戶輸入。等到用戶終于輸入'quit' 后,Python停止執(zhí)行while循環(huán),而整個(gè)程序也到此結(jié)束
另一種表達(dá)方式:
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)
通過設(shè)置標(biāo)志位,如active,并在循環(huán)終交互式的改變標(biāo)志位的布爾值來對(duì)循環(huán)進(jìn)行控制。
另一種表達(dá)方式:
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() + "!")
在嵌套循環(huán)中,引入break來跳出一層循環(huán),break只能跳出其所在的一層循環(huán)。
一個(gè)例子:
current_number = 0
while current_number < 10:
current_number += 1
if current_number %2 == 0:
continue
print(current_number)
在循環(huán)中執(zhí)行continue會(huì)跳過當(dāng)前循環(huán)中continue后的語(yǔ)句,重新判斷循環(huán)條件進(jìn)行新一輪的循環(huán)。
while循環(huán)對(duì)列表/字典操作的例子
列表間移動(dòng)移動(dòng)元素例子:
unconfirmed_user = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_user:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
for confirmed_user in confirmed_users:
print(confirmed_user.title())
刪除包含特定值的所有列表元素例子:
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:#先判斷再執(zhí)行,避免error
pets.remove('cat')
print(pets)
remove一次只能刪一個(gè)特定內(nèi)容的元素。
對(duì)字典操作例子
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat's 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 + ".")
在本章中,你學(xué)習(xí)了:如何在程序中使用input()來讓用戶提供信息;如何處理文本和數(shù)字 輸入,以及如何使用while循環(huán)讓程序按用戶的要求不斷地運(yùn)行;多種控制while循環(huán)流程的方式: 設(shè)置活動(dòng)標(biāo)志、使用break語(yǔ)句以及使用continue語(yǔ)句;如何使用while循環(huán)在列表之間移動(dòng)元素, 以及如何從列表中刪除所有包含特定值的元素;如何結(jié)合使用while循環(huán)和字典。