简单Python测验-多个可接受的答案

简单Python测验-多个可接受的答案,python,python-3.x,Python,Python 3.x,我是一个初学者,所以要友善;) 我正在做一个小测验,并试图让它接受问题2的“js”和“j.s”,以及问题3的“4”和“4”。但我还不知道怎么做 另外,我将answer=input(question.prompt).lower()放在下面,这样它就可以接受这两种情况。这是正常的做法吗 代码非常松散地基于我在YouTube上看到的一个教程,但请指出我的错误,因为目前这只是一些猜测 # Quiz class Question: def __init__(self, prompt, answe

我是一个初学者,所以要友善;)

我正在做一个小测验,并试图让它接受问题2的“js”和“j.s”,以及问题3的“4”和“4”。但我还不知道怎么做

另外,我将
answer=input(question.prompt).lower()
放在下面,这样它就可以接受这两种情况。这是正常的做法吗

代码非常松散地基于我在YouTube上看到的一个教程,但请指出我的错误,因为目前这只是一些猜测

# Quiz

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer


question_prompts = [
    "1. Who composed 'O mio babbino caro'?",
    "2. Which Bach composed 'Toccata and Fugue in D minor'?",
    "3. How many movements does Beethoven's Symphony No.5 in C minor have?",
    "4. Complete the title: The .... Danube.",
    "5. Ravel's Boléro featured at the 1982 olympics in which sport?",
    "6. Which suite does ‘In the Hall of the Mountain King’ come from? (2 words)",
    "7. Which instrument is the duck in 'Peter and the Wolf'?",
    "8. Which of these is not a real note value - 'hemidemisemiquaver', 'crotchet', 'wotsit' or 'minim?'"
]

questions = [
    Question(question_prompts[0], "puccini"),
    Question(question_prompts[1], "js"),
    Question(question_prompts[2], "four"),
    Question(question_prompts[3], "blue"),
    Question(question_prompts[4], "ice skating"),
    Question(question_prompts[5], "peer gynt"),
    Question(question_prompts[6], "oboe"),
    Question(question_prompts[7], "wotsit"),

]


def run_quiz(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt).lower()
        if answer == question.answer:
            score += 1

    print()
    print("you got", score, "out of", len(questions))
    if score > 1:
        print("Well done!")
    else:
        print("Better luck next time!")


run_quiz(questions)

您可以向问题构造函数传递一组可接受的答案,而不是单个值,如

questions = [
    Question(question_prompts[1], ["js", "j.s"]),
    Question(question_prompts[2], ["four", "4"]),
    # ...
]
那你需要换线

if answer == question.answer:


您已经完成了。

您可以做的是列出可能的答案,如下所示:

问题(问题提示[2]、“4”、“4”)

然后在您的声明中,您可以执行以下操作:
如果回答有问题。回答:


这将检查给定的答案是否在可能性列表中。请注意,我使用引号创建了一个4的字符串,因为input()中的值始终是一个字符串(即使输入只是一个数字)。

您可以为每个问题存储一个正则表达式来验证用户的答案。提示:与其使用
answer==question.answer
,不如使用
answer in question.answers
?(当然还有其他相关的变化)
if answer in question.answer: