首页 > 解决方案 > 如何使相同的代码适用于多个字典?

问题描述

我是 python 新手,我做了一个测验,询问用户他们是否想玩简单、中等或困难的游戏,然后代码会根据用户选择的难度显示问题。我有字典中的所有问题和答案(每个难度都有一本字典,例如用于简单问题和答案的字典和用于困难问题和答案的字典等),并且我有这部分代码来检查用户的答案是否正确或错误。问题是检查答案是否正确的代码部分一次只能使用一个字典。另一个问题是我不知道如何做到这一点,如果用户选择easy,那么代码会从easy dict中打印出简单的问题。这部分if answer.lower() == Question_list_easy[ques]:只允许 1 个字典,这就是为什么我认为代码一次只允许一个字典的原因。我已经尝试过if chooses == "easy": print (Question_list_easy),但它不起作用。请帮我。

import random

quiz_difficulty = input("Would you like to play on easy, medium, or hard\n").lower()
if quiz_difficulty == "easy":
  print (Question_list_easy)
   
if quiz_difficulty == "medium":
   print (Question_list_medium)

if quiz_difficulty == "hard":
   print (Question_list_hard)


Question_list_easy = {
   "How many days are there in a year?":"365",
   "How many hours are there in a day?":"24", 
   "How many days are there in a week?":"7"
   } 

Question_list_medium = {
   "How many weeks are there in a year?":"52",
   "How many years are there in a decade?":"10", 
   "How many days are there in a fortnight?":"14"
   } 

Question_list_hard = {
   "How many years are there in a millennium?":"1000",
   "How many days are there in 2 years?":"730", 
   "How many years are there in a half a century?":"50"
   } 
  


#The part which asks the questions and verifies if the answer the user does is coreect or incorrect. It also randomizes the questions
question = list (Question_list_easy.keys())
#input answer here 
while True:
    if not question:
        break
    ques = random.choice(question)
    print(ques)
    while True:
        answer = input('Answer ' )
        # if correct, moves onto next question
        if answer.lower() == Question_list_easy[ques]:
            print("Correct Answer")
            break
        else:
            #if wrong, Asks the same question again
            print("Wrong Answer, try again")
    question.remove(ques)

标签: pythondictionary

解决方案


这看起来很接近,但我认为你缺少的部分是你可以说:

if quiz_difficulty == "easy":
   question_list = Question_list_easy
if quiz_difficulty == "medium":
   question_list = Question_list_medium
if quiz_difficulty == "hard":
   question_list = Question_list_hard

然后,在您提出问题的部分中,您只需使用question_list而不是专门引用Question_list_easy.


推荐阅读