You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python入门:如何实现选择题测验的多正确选项功能?

如何修改Python选择题测验以支持多个正确选项?

你尝试用"a" or "c"作为正确答案是无效的——Python中"a" or "c"会直接返回"a"(非空字符串为真值,or运算会返回第一个真值),无法实现多正确选项的需求。下面是具体修改方案:

1. 修改Question类(Student.py文件)

将单个答案的存储逻辑改成支持多个答案的集合,既兼容原有单个答案场景,也能处理多正确选项:

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        # 将答案统一转为集合,支持单个字符串或多个答案的列表/元组
        if isinstance(answer, str):
            self.correct_answers = {answer}
        else:
            self.correct_answers = set(answer)

2. 修改主程序代码

  • 定义问题时,多个正确选项用列表或元组传入
  • 调整答题判断逻辑,同时处理输入的大小写和空格,提升用户体验

修改后的主代码:

from Student import Question
question_prompt = [
    "What color are apples?\n(a) Red\n(b) Purple\n(c) Green\n\n",
    "What color are bananas?\n(a) Purple\n(b) Yellow\n(c) Blue\n\n"
]

questions = [
    Question(question_prompt[0], ["a", "c"]),  # 传入多个正确选项的列表
    Question(question_prompt[1], "b")  # 单个正确选项仍用字符串,兼容原有逻辑
]

def run_test(questions):
    score = 0
    for question in questions:
        # 去除输入的首尾空格并转为小写,避免大小写或空格导致的判断错误
        answer = input(question.prompt).strip().lower()
        if answer in question.correct_answers:
            score += 1
    # 用f-string格式化输出,更简洁
    print(f"You got {score}/{len(questions)}")

run_test(questions)

修改完成后,第一个问题用户输入a、c、A甚至c都会被判定为正确,同时保留了原有单个正确选项的功能。

内容的提问来源于stack exchange,提问作者Mateusz Szojda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 11:38:10