在quizzpython上创建一个简单和困难的模式

2024-06-15 09:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写这段python代码,它允许用户选择一个简单的模式和一个有多种选择的硬模式。每个模式的问题都是相同的,但硬版本只是在每个问题中有更多的选项可供选择。这是我目前为止的代码:

questions = ["What is 1 + 1",
         "What is Batman's real name"]
answer_choices = ["1)1\n2)2\n3)3\n4)4\n5)5\n:",
              "1)Peter Parker\n2)Tony Stark\n3)Bruce Wayne\n4)Thomas Wayne\n5)Clark Kent\n:"]
correct_choices = ["2",
               "3",]
answers = ["1 + 1 is 2",
       "Bruce Wayne is Batman"]

def quiz():
    score = 0
    for question, choices, correct_choice, answer in zip(questions,answer_choices, correct_choices, answers):
        print(question)
        user_answer = str(input(choices))
        if user_answer in correct_choice:
            print("Correct")
            score += 1
        else:
            print("Incorrect", answer)
    print(score, "out of", len(questions), "that is", float(score /len(questions)) * 100, "%")

quiz()

我如何添加简单和困难的更多,而不做一个新的列表,不得不复制和粘贴一切?解释一下也不错。 提前感谢您的回复


Tags: 代码answeris模式whatchoicesquestionsscore
3条回答

你可以创建一个所有问题的列表,然后根据难度进行必要的拼接。在

def get_choices(difficulty):
    choices = [
        "1)1\n2)2\n3)3\n4)4\n5)5\n:",
        "1)Peter Parker\n2)Tony Stark\n3)Bruce Wayne\n4)Thomas Wayne\n5)Clark Kent\n:"
    ]

    if difficulty == 'easy':
        choices = [c.split("\n")[:3]  for c in choices]
        return choices
    elif difficulty == 'medium':
        choices = [c.split("\n")[:4]  for c in choices]
        return choices
    else:
        return choices

如果您可以将每个单独的选择都作为一个列表元素,并有一个对应的解决方案,则会更简单。然后你可以得到正确的答案,洗牌其他答案,并自动分配数字。在

您可以定义功能块并根据用户输入调用它们,例如:

# define the function blocks
def hard():
    print ("Hard mode code goes here.\n")

def medium():
    print ("medium mode code goes here\n")

def easy():
    print ("easy mode code goes here\n")

def lazy():
    print ("i don't want to play\n")

# Now map the function to user input
choose_mode = {0 : hard,
           1 : medium,
           4 : lazy,
           9 : easy,

}
user_input=int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
choose_mode[user_input]()

那么功能块的调用将是:

^{pr2}$

实现这一点的一种方法是从一个列表开始,其中包含每个问题的正确答案和可能的错误答案。在

然后,您将创建代码,根据难度级别为每个问题选择正确数量的错误问题,从而从基本列表中生成实际的问题列表。生成的新列表将用于提问。在

相关问题 更多 >