1、用戶輸入和while 循環(huán)
大多數(shù)程序旨在解決最終用戶問題,在程序要一個名字時,需要提示用戶輸入名字,需要名單時,輸入一系列名字,為此需要用到input()函數(shù),來獲取用戶的輸入。
1.1、input()函數(shù)的工作原理
它可以使程序停止,等待用戶輸入,待輸入后,將信息存儲到一個變量中,以方便程序使用:
msg = input('Tell me something, i will repeat it back to you :')
print(msg)
----
輸入'Hello World!'
打印出:
Tell me something, i will repeat it back to you :Hello World!
Hello World!
1.1.1、編寫清晰的程序
提醒用戶輸入的提示信息,可以是一行也可以是多行,當是多行時,可使用字符串分行書寫:
msg = 'If you tell us who you are, we can personalize the message you see.'
msg += "\nWhat's you first name? " # 將后一段提示添加到字符串后面,閱讀起來更清晰
name = input(msg)
print('\nHello ' + name + '!')
-------
Tell me something, i will repeat it back to you.
What's you first name? eric
Hello, Eric!
1.1.2、使用int()來獲取數(shù)值輸入
使用input()函數(shù),python解讀的時字符串,有時需要用到數(shù)字時,就要用到int()函數(shù)了,它可以將字符串轉換成整型。
>>> age = input('how old are you? ')
how old are you? 21 # 獲得是字符串,顯然不符合需求
>>> age
'21'
>>> age = int(input('how old are you? ')) # 在input()前加一個int()函數(shù),將字符串轉換成整型
how old are you? 21
>>> age
21
1.1.3、求模運算符(%)
求模運算符(%),指的是求兩個數(shù)的余數(shù),利用此可以判斷這個數(shù)是奇數(shù)還是偶數(shù):
num = int(input('enter a number, i will tell you this number is even or odd: '))
if num % 2 == 0: # 如果這個數(shù)除以2,余數(shù)為0則為偶數(shù),否則為奇數(shù)
print('this number ' + str(num) + ' is a even.') # 數(shù)字和字符串不能直接相連接,數(shù)字要轉換成字符串
else:
print('this number ' + str(num) + ' is a odd.')
enter a number, i will tell you this number is even or odd: 23
this number 23 is a odd.
1.2、while 循環(huán)
for循環(huán)可以用來遍歷字典、列表、元組等中的每個元素,if語句只能每次執(zhí)行一次,而while循環(huán)可以重復循環(huán),直至達到滿足條件為止。
1.2.1、使用while 循環(huán)
while 循環(huán),首先判斷條件是否為真,真則執(zhí)行循環(huán)體,假則結束循環(huán):
# 利用while 循環(huán)數(shù)數(shù)
current_num = 1
while current_num <= 5: # 只要current_num <= 5,程序就會繼續(xù)循環(huán)下去,直至大于5
print(current_num)
current_num += 1
1.2.2、讓用戶選擇何時退出
while 循環(huán)可以使程序不斷運行下去,直至條件為假(用戶想要它停止時),如下,我們定義了一個退出值,可以結束循環(huán):
# 定義了一個退出值(quit)
prompt = '\nTell me something, I will repeat it back to you:'
prompt += "\nEnter 'quit' to end of program. "
msg = ''
while msg != 'quit': # 當用戶輸入的不是quit時循環(huán)執(zhí)行,打印信息,當是quit時循環(huán)終止
msg = input(prompt)
if msg != 'quit':
print(msg)
-----------------------------
Tell me something, and i will repeat it back to you:
Enter 'quit' to end of program.hello world
hello world
Tell me something, and i will repeat it back to you:
Enter 'quit' to end of program.
1.2.3、使用標志
我們可以讓程序在指定條件下運行,但在更加復雜的程序中,很多事件能導致程序停止運行,這種情況下不可能使用很多條while語句去檢查所有條件,即增加了代碼量也不便于閱讀,這時我們可以定義一個變量,用來判斷程序是否處于活動狀態(tài),這個變量稱為標志,為True時,程序繼續(xù)運行,并在任何事件導致的值為False時讓程序停止運行,這樣while只需檢查一次條件即可。
prompt = '\nTell me somethin, I will repeat it back to you:'
prompt += "\nEnter 'quit' to end of program. "
active = True # 首先定義一個變量,初始值為True,while才能運行,變量名隨意
while active:
msg = input(prompt)
if msg == 'quit': # 當用戶輸入quit時,變量active變?yōu)镕alse,循環(huán)終止
active = False
else:
print(msg)
1.2.4、使用break 退出循環(huán)
要立即退出while 循環(huán),不再運行循環(huán)中余下代碼,也不管條件測試結果如何,可使用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() + '.')
print('Down!') # break語句跳出循環(huán)后執(zhí)行該條語句
1.2.5、在循環(huán)中使用continue
continue語句可以中止當前循環(huán),跳到循環(huán)開頭,進行下一次循環(huán),在進行循環(huán)的時候會檢查循環(huán)條件:
current_num = 0
while current_num < 10:
current_num += 1
if current_num % 2 == 0: # 當為偶數(shù)時,求模為0,中止當前循環(huán),跳到循環(huán)開頭,重新判斷條件
continue
print(current_num) # 如果不能被2整除,則執(zhí)行余下代碼
1
3
5
7
9
1.2.6、避免無限循環(huán)
每個while循環(huán)必須有停止運行的途徑,這樣才不會一直執(zhí)行下去,要避免死循環(huán),應該對while循環(huán)進行測試;如果希望程序在用戶輸入特定值時結束,可運行程序并輸入這樣的值,如果在這種情況下程序沒有結束,則要檢查程序處理這個值的方式,至少保證有一個這樣的地方能讓循環(huán)條件False或讓break語句得以執(zhí)行。
當進行死循環(huán)時可以按ctrl + c 停止:
x = 1 # 由于x的值是個常量,一直小于5,程序進入死循環(huán)
while x < 5:
print(x)
練習
# 電影票根據(jù)年齡來收取價格,首先詢問顧客年齡
prompt = '\nHow old are you?'
prompt += "\nEnter 'quit' when you finished. "
while True:
age = input(prompt)
if age == 'quit': # 如果谷歌輸入quit則跳出循環(huán)
break
age = int(age) # 由于input()函數(shù)python接收的是字符串,需要轉換成數(shù)字
if age < 3:
print('You get in free!')
elif 3 <= age <= 12:
print('You ticket is 10$.')
else:
print('You ticket is 15$.')
1.3、使用while 循環(huán)來處理列表和字典
要記錄大量的用戶和信息,需要在while 循環(huán)中使用列表和字典,for 循環(huán)遍歷列表難以跟蹤其中的元素,要在遍歷的同時對其進行修改,可使用while 循環(huán),通過將while 循環(huán)同列表和字典結合起來使用,可收集、存儲并組織大量輸入,以供查看和顯示。
1.3.1、在列表間移動元素
假設有個列表,包含注冊但未驗證的用戶,驗證后將他們移動到一個已經(jīng)驗證過的列表中:
uncofirmed_users = ['alice', 'brian', 'candace'] # 未驗證
confirmed_users = [] # 創(chuàng)建一個驗證過的用戶空列表
while uncofirmed_users: # 循環(huán)一直運行,直到列表為空
current_users = unconfirmed_users.pop() # 彈出列表最后一個元素,把它存儲到變量xxx中
print('Verfying users: ' + current_users.title())
confirmed_users.append(current_users) # 把這個變量存儲到空列表中
print('\nThe following users have been confirmed:')
for confirmed_user in confirmed_users: # 遍歷第二個列表
print(confirmed_user)
-------------------------------------
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
1.3.2、刪除包含特定值的所有列表元素
在列表中我們學習了如何用remove()刪除列表中的特定值,但是它只能刪除列表中同種元素的第一個值,其他的不能刪除。
# 一個包含很多寵物的列表,要刪除里面所有的cat
pets = ['dogs', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets: # 進入循環(huán)后,發(fā)現(xiàn)'cat'在列表至少存在一次,python刪除第一個'cat',并返回到while代碼行,發(fā)現(xiàn)還有'cat',繼續(xù)刪除,直到刪除所有為止
pets.remove('cat')
print(pets)
------
['dogs', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dogs', 'dog', 'goldfish', 'rabbit']
1.3.3、使用用戶輸入來填充字典
可使用while 循環(huán)來提示用戶輸入任意數(shù)量的信息
# 創(chuàng)建一個調(diào)查程序,記錄調(diào)查者的名字,喜歡的山,并將數(shù)據(jù)存儲到一個字典中
responses = {}
# 設置一個標志,指出調(diào)查是否繼續(xù)
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
# 詢問是否還有人要參與調(diào)查
repeat = input('Would you like to let another person respond? (Yes/ No)')
# 如果沒有則標志的值為假,循環(huán)中止
if repeat == 'No':
polling_active = False
# 打印結果,顯示結果
print('\n--- Poll Result ---')
for name, response in responses.items():
print(name + ' would like to climb ' + response + '.')
--------------------------------
What is your name? alice
Which mountain would you like to climb someday? denali
Would you like to let another person respond? (Yes/ No)No
--- Poll Result ---
alice would like to climb denali.
關于上面的這個例子是如何將名字和回答添加到字典中
>>> responses = {}
>>> name = 'alice'
>>> response = 'denali'
>>> responses[name] = response # 字典名+[存儲鍵的變量] = 存儲值的變量
>>> print(responses) # 區(qū)別于訪問字典中的值,responses['alice']
{'alice': 'denali'}