我是个初学者,所以要友善一点;)
我正在做一个小测验,试图让它同时接受问题2的"js“和”js“,以及问题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)发布于 2020-07-31 06:02:38
您可以向问题构造函数传递一组可接受的答案,而不是单个值,如下所示
questions = [
Question(question_prompts[1], ["js", "j.s"]),
Question(question_prompts[2], ["four", "4"]),
# ...
]然后,您需要更改行
if answer == question.answer:至
if answer in question.answer:你就完事了。
发布于 2020-07-31 06:05:03
你可以像下面这样列出可能的答案:
Question(question_prompts[2], ["four", "4"])
然后在你的of语句中你可以这样做:if answer in question.answer:
这将检查给定的答案是否在可能性列表中。请注意,我使用引号生成了一个4的字符串,因为来自input()的值始终是一个字符串(即使输入只是一个数字)。
https://stackoverflow.com/questions/63181927
复制相似问题