首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简单的Python测验-多个可接受的答案

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

Stack Overflow用户
提问于 2020-07-31 05:55:00
回答 2查看 42关注 0票数 1

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

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

另外,我把answer = input(question.prompt).lower()放在这里,这样它就可以接受这两种情况。这是正常的方式吗?

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

代码语言:javascript
复制
# 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)
EN

回答 2

Stack Overflow用户

发布于 2020-07-31 06:02:38

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

代码语言:javascript
复制
questions = [
    Question(question_prompts[1], ["js", "j.s"]),
    Question(question_prompts[2], ["four", "4"]),
    # ...
]

然后,您需要更改行

代码语言:javascript
复制
if answer == question.answer:

代码语言:javascript
复制
if answer in question.answer:

你就完事了。

票数 1
EN

Stack Overflow用户

发布于 2020-07-31 06:05:03

你可以像下面这样列出可能的答案:

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

然后在你的of语句中你可以这样做:if answer in question.answer:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63181927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档