【Python】07 用戶輸入和while循環(huán)

前言:函數(shù)input(),使用while循環(huán)讓程序不斷地運行,編寫交互式程序

7.1 函數(shù)input()

接受一個參數(shù),即要向用戶顯示的提示或者說明。

編寫清晰度程序,提示清晰且易于理解

prompt = 'if you tell us who you are, we can personalize the messages you see.'
prompt +='\nwhat is your name?' #用+=號處理超過一行的提示

7.1.2 使用int()來獲取數(shù)值輸入

#rollercoaster.py
height = input('how tall are you, in inches?')
height = int(height)

if height >=36:
    print("\nyou're tall enough to ride!")
else:
    print("\nyou'll be able to ride when you're a little older.")

7.1.3 求模運算符 %:兩個數(shù)相除并返回余數(shù)

4%3
#返回1

Tips:可以用求模數(shù)判斷數(shù)字是奇數(shù)還是偶數(shù),返回0即為偶數(shù)

7.2 while循環(huán)

for循環(huán)是針對集合中的每個元素的一個代碼塊,while循環(huán)則不斷進行,知道指定的條件不滿足為止。

7.2.2 讓用戶選擇何時退出

prompt = 'if you tell us who you are, we can personalize the messages you see.'
prompt += "\nenter 'quit' to end the program." #用+=號處理超過一行的提示
message = ''
while message != 'quit':
      message = input(prompt)
       
      if message != 'quit':
      print(message)

7.2.3 使用標志

讓程序在標志為True的時候繼續(xù)運行,為False的時候停止運行。

prompt = 'if you tell us who you are, we can personalize the messages you see.'
prompt += "\nenter 'quit' to end the program." #用+=號處理超過一行的提示

active = True
while active:#可以給標志指定任何名稱
    message = input(prompt)
    
    if message == 'quit':
        active = False
    else:
        print(message)

7.2.4 使用break退出循環(huán)

break語句用于控制程序流程,立即退出while循環(huán),不再運行循環(huán)中余下的代碼。

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()+'!')

輸出結(jié)果:


輸出.png

7.2.5 在循環(huán)中使用continue

返回循環(huán)開頭,并根據(jù)條件測試結(jié)果決定是否繼續(xù)執(zhí)行循環(huán)。

current_number = 0
while current_number < 10:
    current_number +=1
    if current_number % 2 == 0:
        continue
        
    print(current_number)

輸出結(jié)果:


輸出2.png

7.2.6 避免無限循環(huán)

如果程序陷入無限循環(huán),可以command+C,也可關(guān)閉顯示程序輸出的終端窗口。
確認程序至少有一個地方可以讓循環(huán)條件為False或者讓break語句得以執(zhí)行。

7.3 用while循環(huán)來處理列表和字典

在for循環(huán)中不應(yīng)修改列表,會導(dǎo)致難以跟蹤其中的元素。通過將while循環(huán)同列表和字典結(jié)合起來,可收集、存儲并組織大量輸入,供查看和顯示。

7.3.1 在列表之間移動數(shù)據(jù)

#首先創(chuàng)建一個待驗證用戶列表和一個已驗證用戶列表
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []

#驗證每個用戶,直到?jīng)]有未驗證用戶
#將經(jīng)過驗證的用戶轉(zhuǎn)移到已驗證用戶列表
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())

輸出結(jié)果:


輸出3.png

7.3.2 刪除包含特定值的所有列表元素

單獨使用remove()可以刪除第一個值;刪除所有值,需要使用while循環(huán)

pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
while 'cat' in pets:
    pets.remove('cat')
print(pets)

輸出:['dog', 'dog', 'goldfish', 'rabbit']

7.3.3 使用用戶輸入來填充字典

responses = {}
#設(shè)置一個標志,指出調(diào)查是否繼續(xù)
polling_active = True

while polling_active:
    #提示輸入被調(diào)查者的名字和回答
    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)")
    if repeat == 'no':
        polling_active = False
        
#調(diào)查結(jié)束,顯示結(jié)果
print("\n---poll results---")
for name,response in responses.items():
    print (name + " would like to climb " + response + '.')

輸出結(jié)果:


輸出4.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容