一、input() 函數的工作原理
input() 函數讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入后,Python 將其賦給一個變量,以便使用。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)'''
結果:
Tell me something, and I will repeat it back to you: Hi, xiaolouo
Hi, xiaolouo
'''
1.?int() 來獲取數值輸入
在使用 input() 函數時,Python 會將用戶輸入解讀為字符串。
>>> age = input('How old are you?') How old are you?21
>>> age
'21'
當試圖將該輸入用于數值比較時,Python 會報錯,因為它無法將字符串和整數進行比較
>>> age >= 18
Traceback (most recent call last): File "<python-input-2>", line 1, in <module>
age >= 18 TypeError: '>=' not supported between instances of 'str' and 'int'
為了解決這個問題,可使用函數 int() 將輸入的字符串轉換為數值,確保能夠成功地執行比較操作:
>>> age = int(age)
>>> age >= 18
True
2.?求模運算符
求模運算符(%)是個很有用的工具,它將兩個數相除并返回余數:
>>> 4 % 3
1
>>> 5 % 3
2
二、while 循環簡介
for 循環用于針對集合中的每個元素執行一個代碼塊,而 while 循環則不斷地運行,直到指定的條件不再滿足為止
1.?使用 while 循環
可以使用 while 循環來數數。例如,下面的 while 循環從 1 數到 5:
current_number = 1
while current_number <= 5:print(current_number)current_number += 1'''
結果:
1
2
3
4
5
'''
2.?讓用戶選擇何時退出
我們在其中定義了一個退出值,只要用戶輸入的不是這個值,程序就將一直運行:
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'q' to end the program."
message = ''
while message != 'q':message = input(prompt)print(message)
'''
結果:
Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.w
wTell me something, and I will repeat it back to you:
Enter 'q' to end the program.r
rTell me something, and I will repeat it back to you:
Enter 'q' to end the program.q
q'''
3.?使用標志
在要求滿足很多條件才繼續運行的程序中,可定義一個變量,用于判斷整個程序是否處于活動狀態。這個變量稱為標志(flag),充當程序的交通信號燈。可以讓程序在標志為 True 時繼續運行,并在任何事件導致標志的值為False 時讓程序停止運行。這樣,在 while 語句中就只需檢查一個條件:標志的當前值是否為 True。
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'q' to end the program."
message = ''
active = True
while active:message = input(prompt)if message == 'q':active = Falseelse:print(message)'''
結果:
Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.1
1Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.2
2Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.q
'''
4.?使用 break 退出循環
如果不管條件測試的結果如何,想立即退出 while 循環,不再運行循環中余下的代碼,可使用 break 語句。break 語句用于控制程序流程,可用來控制哪些代碼行將執行、哪些代碼行不執行,從而讓程序按你的要求執行你要執行的代碼。
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'q' to end the program."
message = ''
while True:city = input(prompt)if city == 'q':breakelse:print(f"I'd love {city}.")'''
結果:
Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.sh
I'd love sh.Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.yn
I'd love yn.Tell me something, and I will repeat it back to you:
Enter 'q' to end the program.q'''
5.?在循環中使用 continue
要返回循環開頭,并根據條件測試的結果決定是否繼續執行循環,可使用continue 語句,它不像 break 語句那樣不再執行余下的代碼并退出整個循環。例如,來看一個從 1 數到 10,只打印其中奇數的循環:
current_number = 0
while current_number < 10:current_number += 1if current_number % 2 == 0:continueprint(current_number)'''
結果:
1
3
5
7
9
'''
三、使用 while 循環處理列表和字典
通過將 while 循環與列表和字典結合起來使用,可收集、存儲并組織大量的輸入,供以后查看和使用。
1.?在列表之間移動元素
# 首先,創建一個待驗證用戶列表
# 和一個用于存儲已驗證用戶的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 驗證每個用戶,直到沒有未驗證用戶為止
# 將每個經過驗證的用戶都移到已驗證用戶列表中
while unconfirmed_users:current_user = unconfirmed_users.pop()print(f"Verifying user: {current_user}")confirmed_users.append(current_user)
# 顯示所有的已驗證用戶
print("\nThe following users are confirmed:")
for confirmed_user in confirmed_users:print(confirmed_user.title())'''
結果:
Verifying user: candace
Verifying user: brian
Verifying user: aliceThe following users are confirmed:
Candace
Brian
Alice'''
2.?刪除為特定值的所有列表元素
pets = ['dog', 'cat', 'goldfish', 'cat', 'rabbit']
print(pets)
while 'cat' in pets:pets.remove('cat')
print(pets)'''
結果:
['dog', 'cat', 'goldfish', 'cat', 'rabbit']
['dog', 'goldfish', 'rabbit']'''
3.?使用用戶輸入填充字典
可以使用 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? [Y/N]")if repeat == 'no':polling_active = False
print("\n--- Poll Results ---")
for name, responses in responses.items():print(f"{name}: {responses}")'''
結果:
What is your name? zhnagsan
Which mountain would you like to climb someday?taishan
Would you like to let another person respond? [Y/N]YWhat is your name? lisi
Which mountain would you like to climb someday?yueshan
Would you like to let another person respond? [Y/N]NWhat is your name? wangwu
Which mountain would you like to climb someday?qianlishan
Would you like to let another person respond? [Y/N]no--- Poll Results ---
zhnagsan: taishan
lisi: yueshan
wangwu: qianlishan
'''