如何为Python总统测试程序实现多可选正确答案匹配?
美国总统知识测试程序:实现多答案匹配功能
你当前的程序只能匹配单一正确答案,无法识别用户输入的变体(比如简称、全名省略中间名等)。之前用"eleventh":"James K. Polk" or "James Polk"的写法无效,是因为Python中or运算符会返回第一个非空字符串,实际字典值还是"James K. Polk",根本没实现多选项。
用列表存储多个正确答案是完全可行的,以下是具体实现步骤:
1. 修改字典结构,用列表存储多答案
把每个总统对应的所有正确变体放到列表里,示例如下:
presidents = { "first": ["George Washington"], "second": ["John Adams"], "third": ["Thomas Jefferson"], "eleventh": ["James K. Polk", "James Polk"], "thirty fifth": ["John F. Kennedy", "John Kennedy", "JFK"], # 其他总统按此格式补充 }
2. 修改答案判断逻辑
不再直接比较字符串是否相等,而是检查用户输入的小写形式是否存在于正确答案的小写列表中。
修改后的完整代码
import random def main(): # 每个键对应的值是包含所有正确答案变体的列表 presidents = { "first": ["George Washington"], "second": ["John Adams"], "third": ["Thomas Jefferson"], "fourth": ["James Madison"], "fifth": ["James Monroe"], "sixth": ["John Quincy Adams"], "seventh": ["Andrew Jackson"], "eighth": ["Martin Van Buren"], "ninth": ["William Henry Harrison"], "tenth": ["John Tyler"], "eleventh": ["James K. Polk", "James Polk"], "twelfth": ["Zachary Taylor"], # 修正原代码拼写错误:twelth → twelfth "thirty second": ["Franklin D. Roosevelt", "Franklin Roosevelt", "FDR", "Roosevelt"] } wrong = [] print("President Test \n") incorrect_answers = False while len(presidents) > 0: pick = random.choice(list(presidents.keys())) correct_answers = presidents.get(pick) print(f"Who was the {pick} President of the United States?") answer = input("Your answer?: ") # 将用户输入和所有正确答案统一转为小写后检查是否匹配 if answer.lower() in [ans.lower() for ans in correct_answers]: print("That's Correct!\n") del presidents[pick] else: print("That's Incorrect.") # 显示最完整的正确答案(列表第一个元素) print("The correct answer is", correct_answers[0]) wrong.append(pick) incorrect_answers = True print(f"You missed {len(wrong)} Presidents.\n") if incorrect_answers: print("Here are the ones that you may want to brush up on:\n") for each in wrong: print(each) else: print("Perfect!") main()
关键说明
- 字典值改为列表后,可以无限添加正确答案变体,满足多种输入形式的需求
- 用
[ans.lower() for ans in correct_answers]生成所有正确答案的小写列表,再检查用户输入的小写是否在其中,实现不区分大小写的匹配 - 修正了原代码中的拼写错误:
twelth改为twelfth - 错误提示时显示列表第一个元素(完整全名),保证用户获得标准答案
内容的提问来源于stack exchange,提问作者A. K. M.
相关产品推荐
相关产品推荐

