目錄
一、函數 input() 的原理
函數 input() 讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入後,python將其存儲在一個變量中,以方便使用。
message = input("Tell me something and I will repeat it back to you: ")
print(message)
1.1 編寫清晰的程序
input() 函數接受一個參數,可以向用戶清晰且易於明白地指出希望用戶輸入的信息。
name = input("Please input your name: ")
print("Hello, " + name + "!")
⚠️使用python3解釋器,input()可以直接辨別輸入的字符串,但是python2解釋器輸入字符串需要加“”.
pycharm默認了python2解釋器。
已解決!
在這裏,添加python解釋器
設置運行文件時,選擇解釋器python3.7。
有時,提示語句可能超過一行,此時可將提示語句存儲在一個變量中。
prompt = "If you tell us you are, we can personalize the message you see."
prompt +="\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name +"!")
1.2 使用 int() 來獲取數值輸入
使用函數 input() 時,python解釋器將用戶的輸入解讀爲字符串格式。
age = input("How old are you?")
print(type(age))
<class 'str'>
使用函數 int() ,可以將數字的字符串表示轉換爲數值表示。
e.g.1 判斷一個人是否滿足坐過山車的身高。
height = input("How tall are you, in inches? ")
height = int(height)
if height>=36:
print("\nYou are tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
1.3 求模運算
求模運算符% :將兩數相除並返回餘數。
若一個數可被另一個數整除,餘數爲0,可利用這一點判斷奇/偶數。
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.")
python 2.7中,使用 raw_input() 來獲取用戶輸入,raw_input() 也將用戶輸入解讀爲字符串格式;
python 2.7也包含 input() ,將用戶輸入解讀爲python代碼,並嘗試運行;python 2.7下,最好使用 raw_input() 來獲取用戶輸入。
二、while 循環簡介
for 循環針對集合中的每一個元素都執行同一段代碼;while 循環不斷運行,知道滿足指定的條件爲止。
2.1 使用 while 循環
使用 while 循環計數。
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
2.2 讓用戶選擇何時退出
定義一個退出值,用戶輸入爲退出值時退出,否則繼續運行。
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)
2.3 使用標誌
在要求很多條件都滿足時才繼續運行程序時,可定義一個變量,用於判斷整個程序是否處於活動狀態,這個變量稱爲標誌。
while 循環只需要判斷標誌是否爲"True",改變標誌值的其他條件可以使用if 語句判斷。
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)
2.4 使用 break 退出循環
- 立即退出循環
- 在任何Python循環中都可使用break語句。e.g. 可以使用break 退出遍歷列表或字典的for循環。
prompt = "\nPlease enter the name of a city you have visited: "
prompt += "\nEnter 'quit' when you are finished. "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
2.5 在循環中使用continue
返回至循環開頭,並根據條件測試結果決定是否繼續執行循環。只結束單次循環
e.g. 只打印10以內的奇數。
(理解:if 語句檢查current_number 與2的求模運算的結果,若結果爲0,執行 continue 語句,忽略餘下的代碼並返回到循環的開頭;若當前的數字不能被2整除,就執行循環中餘下的代碼。)
current_number = 0
while current_number < 10:
current_number +=1
if current_number %2 ==0:
continue
else:
print(current_number)
2.6 避免無限循環
- 當程序陷入無限循環時,“control +C” 結束程序;
- 務必對每個 while 循環進行測試,確保其如預期那樣結束
練習
電影票:有家電影院根據觀衆的年齡收取不同票價:不到3歲的觀衆免費;3~12歲觀衆爲10美元;超過12歲的觀衆爲15美元。編寫一個while 循環,在其中詢問用戶的年齡,並指出其票價。
- 在while 循環中使用條件測試來結束循環
- 使用變量active來控制循環結束的時機
- 使用break語句在用戶輸入'quit'時退出循環
prompt = "How old are you? Please input your age: "
active = True
while active:
age = input(prompt)
if age =='quit':
break
else:
age = int(age) #!!!<class 'str'> --> <class 'int'>
if age < 3:
print("Free.")
elif age <= 12:
print("10$.")
else:
print("15$.")
三、使用 while 循環處理列表和字典
- for循環時遍歷列表的有效方式,但在for循環中不應修改列表(否則將導致python難以跟蹤其中的元素)
- 使用while循環在遍歷列表的同時修改列表,將while循環與列表、字典結合使用,可收集、存儲並組織大量輸入,供以後查看
3.1 在列表之間移動元素
空列表作爲判斷條件時,爲False。
# 首先,創建一個待驗證用戶列表
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())
3.2 刪除包含特定值的所有列表元素
e.g 假設有一個寵物列表,其中包含多個值爲'cat'的元素,刪除所有這些元素。
(remove() 只刪除第一個匹配的元素)
pets = ['dog','cat','dog','goldfish','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
3.3 使用用戶輸入來填充字典
e.g 使用while循環提示用戶輸入任意數量的信息,並將用戶的名字和回答存儲在一個字典中。
responses = {}
# 設置一個標誌,指出調查是否繼續
polling_active = True
while polling_active:
# 提示輸入被調查者的名字和回答
name = input("\nWhat's your name? ")
response = input("\nWhich mountain would you like to climb someday? ")
# 將答案存儲在字典中
responses[name] = response
#查看是否有人蔘與調查
repeat = input("Would you like to let another person repond?(yes/no)")
if repeat == 'no':
polling_active = False
# 調查結果,顯示結果
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name.title() + " would like to climb " + response + ".")