我在使用 Python 字典和用户输入时遇到问题

我在处理这段代码时遇到了问题。基本上我要求用户输入一个问题,然后它要求用户回答。这些都存储在字典中。我能够存储问题,但是当通过输入 #1 来回忆答案时,它会返回问题两次。知道为什么吗?


#start title screen


title = "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 answers

faq = {}


done = False


while 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!")


小怪兽爱吃肉
浏览 90回答 1
1回答

慕码人8056858

在这两个循环中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]))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python