如何让Python测验程序的单道题目支持多个正确答案?
解决方案
你可以将answers调整为嵌套列表,让苹果对应的正确答案包含多个选项,再通过in关键字判断用户输入是否属于正确选项集合。
原写法的问题
你之前尝试的"red" or "green"和"red" and "green"是Python的逻辑运算:
"red" or "green"会返回第一个布尔值为真的表达式,也就是"red""red" and "green"会返回最后一个布尔值为真的表达式,也就是"green"
所以这两种方式都无法实现多答案匹配的需求。
修改后的代码
方式一:统一用嵌套列表存储答案
questions = ["what colour are apples?", "what colour are bananas?"] # 每个问题的正确答案都用列表存储,支持多个选项 answers = [["red", "green"], ["yellow"]] for idx in range(len(questions)): user_answer = input(questions[idx]).lower() if user_answer in answers[idx]: print("correct")
方式二:兼容单个/多个答案的写法
如果部分问题只有单个正确答案,也可以保留原格式,通过类型判断统一处理:
questions = ["what colour are apples?", "what colour are bananas?"] answers = [["red", "green"], "yellow"] for idx in range(len(questions)): user_answer = input(questions[idx]).lower() # 将单个答案转为列表,统一判断逻辑 correct_options = answers[idx] if isinstance(answers[idx], list) else [answers[idx]] if user_answer in correct_options: print("correct")
内容的提问来源于stack exchange,提问作者Aj 151
相关产品推荐
相关产品推荐

