一、用戶輸入
1、函數input()的工作原理
函數input()讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入后,Python將其存儲在一個變量中,以方便你使用。函數input()接受一個參數,即要向用戶顯示的提示或說明,讓用戶知道該怎么做。
message = input("Tell me something,and I will repeat it back to you.")
print(message)
注:提示末尾(這里是冒號后面)包含一個空格,可將提示和用戶輸入分開,讓用戶清楚知道其輸入始于何處。
message = "Tell me something,and I will repeat it back to you."
message += "\nNow what do you want to say? "
prompt = input(message)
print(message)
注:上述代碼展示了提示超過一行的處理方法,將提示存儲在一個變量中,再將這個變量傳遞給函數input()。
2、使用int()來獲取數值輸入
使用函數input()時,Python將用戶輸入解讀為字符串。將數值輸入用于計算和比較時,務必將其轉換為數值表示。
number = input("Enter a number,and I will 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.")
注:求模運算符%常用來判斷一個數的奇偶性。
3、在Python 2.7中獲取輸入
應使用raw_input()來提示用戶輸入,也將輸入解讀為字符串。
二、while循環
for循環用于針對集合中的每個元素都一個代碼塊,而while循環不斷地運行,直到指定的條件不滿足為止。
1、使用while循環
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
#使用標志
active = True
while active:
messsage = input(prompt)
if message == 'quit':
active = False
else:
print(message)
注:在要求很多條件都滿足才繼續運行的程序中,可定義一個變量,用于判斷整個程序是否處于活動狀態,這個變量被稱為標志,充當了程序的交通信號燈。程序在標志位True時繼續運行,并在任何事件導致標志的值為False時讓程序停止運行。這樣,在while語句中就只需要檢查一個條件——標志的當前值是否為True,并讓所有測試(是否發生了應將標志設置為False的事件)都放在其他地方,從而讓程序變得更為整潔。
2、退出循環
- break 退出循環,不再運行循環中余下的代碼
- continue 退出當前循環,返回循環開頭
注:應避免無限循環,若程序陷入無限循環,可按Ctrl+C,也可關閉顯示程序輸出的終端窗口。
3、使用while循環來處理列表和字典
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)
② 刪除包含特定值的所有列表元素
pets = ['dog','cat','rabbit','cat','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
③ 使用用戶輸入來填充字典
responses = []
#設置一個標志,指出調查是否繼續
polling_active = True
while pollint_active:
#提示輸入被調查者的姓名和回答
name = input("\nWhat is your name? ")
responses = input("\nWhich color would you like best? ")
#將答案存儲在字典中
responses[name] = responses
#看看是否還有人要參與調查
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 + " like " + response +" best!")