亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我在使用 Python 字典和用戶輸入時遇到問題

我在使用 Python 字典和用戶輸入時遇到問題

小怪獸愛吃肉 2023-05-09 16:13:09
我在處理這段代碼時遇到了問題?;旧衔乙笥脩糨斎胍粋€問題,然后它要求用戶回答。這些都存儲在字典中。我能夠存儲問題,但是當通過輸入 #1 來回憶答案時,它會返回問題兩次。知道為什么嗎?#start title screentitle = "Frequently Asked Questions" print()  print("=" * len(title))print(title)print("=" * len(title))  print()#start menu list  menu = """ 0: Exit   1: List FAQ's  2: Add FAQ  3: Delete FAQ  """  #title for selection #1  def faq_title():       print("Frequently Asked Questions:")      print("===========================")  #empty dictionary to be filled with user input questions and answersfaq = {}done = Falsewhile not done:     print(menu)      #enter a choice number      selection = input("Please enter a choice: ")      print()     # if user enters #0 then quits     if selection == "0":          done = True     #if user enters #1, gets list from dictionary named "faq"      elif selection == "1":           faq_title()          for question in faq:             print("Question: {}".format(question))          for answer in faq:              print("Answer: {}".format(answer))  #if user enters #2, user enters a question and then an answer which is to be stored into "faq" dictionary  #user can add as many Q&A as they want to be stored in "faq" dictionary     elif selection == "2":          question = input("Please enter the question: ")          answer = input("Please enter the answer: ")         if question in faq:             print('That question is already listed. Enter another question.')         else:              faq[question] = answer              print('Has been added to the dictionary.')      #if user enter #3, user enters a question to be deleted from the list.     #if list is empty or not in list, then return could not find      elif selection == "3":          delete = input("Please enter the question to be deleted:")          if delete in faq:              del faq[question]          if delete not in faq:              print("Could not find {} in the FAQ's:".format(delete))             print("No changes made")  print("Done!")
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

在這兩個循環中


for question in faq:  

    print("Question: {}".format(question))  

for answer in faq:  

    print("Answer: {}".format(answer)) 

您遍歷字典的相同鍵faq。您在第一個循環中打印所有問題,然后在第二個循環中再次打印所有問題。


你應該做的是:


for question in faq:

    print("Question: {}".format(question))

    print("Answer: {}".format(faq[question]))


查看完整回答
反對 回復 2023-05-09
  • 1 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號