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



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

我正在做一个小测验,并试图让它同时接受";js";以及";j.s";对于问题2;四";以及";4〃;对于问题3。但我还不知道该怎么做。

此外,我放置了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)

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

questions = [
Question(question_prompts[1], ["js", "j.s"]),
Question(question_prompts[2], ["four", "4"]),
# ...
]

然后你需要更改线路

if answer == question.answer:

if answer in question.answer:

你就完了。

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

Question(question_prompts[2], ["four", "4"])

然后在您的of语句中,您可以执行以下操作:if answer in question.answer:

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

相关内容

最新更新