五、使用者輸入和while迴圈

鹤比纷恆红發表於2024-07-27

5.1 函式input()工作原理

# 變數=input(引數:說明/提示)
message input("Tell me something,and I will repeat it back to you:"
print(message)

prompt ="If you tell us who you are,we can personalize the messages you see."
# prompt=prompt+"\nWhat is your first name.?"的簡寫(好用)
prompt += "\nWhat is your first name?
name = input(prompt)
print(f"\nHello,{name}!")

5.2 while

current number = 1
while current_number <=5:
    print(current_number)
    # current number current number + 1
    current_number += 1

5.3 使用while迴圈處理列表和字典

#首先,創健一個末驗證使用者列婊
#和一個用於儲存已驗證使用者的空列表
unconfirmed_users ['alice','brian','candace']
confirmed_users =[
#驗證每個使用者,直到沒有末驗證使用者為止。
#將每個經定過驗證的使用者都移到已驗證使用者列表中
while unconfirmed_users:
    current_user unconfirmed_users.pop()
    print(f"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())
# 刪除為特定值的所有的列表元素
pets ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)

while 'cat'in pets:
	pets.remove('cat')
# 使用使用者輸入來填充字典
#創健1個空字典
responses ={}
#設定一個標誌,指出調查是否繼續。只要為True,pythona就執行whie迴圈中的/程式碼
polling_active True
while polling_active:
	name input("\nWhat is your name?"
	mountain_name input("Which mountain would you like to climb someday?")
	responses[name]mountain_name
	repeat input("Would you like to let another person respond?(yes/no)")
	if repeat =='no':
		polling_active False
#調查結束,顯示結果
print("\n--Poll Results--")
for name,mountain_name in responses.items():# 字典屬於不可迭代物件,需要加items才能在for中迴圈
	print(f"{name}would like to climb {mountain_name}.")

相關文章