Python调用题库API获取随机测验题及打印错题的问题排查
修复后方案
报错根因
- API返回的根节点仅存在
questions数组,prompt是数组内单道题目的属性,你编写的random_question()函数直接访问顶级the_questions['prompt']必然触发KeyError - 原有逻辑存在冲突:同时遍历全量题目又调用随机抽题函数,既没有实现抽10题的需求,还会出现题目和选项不匹配的问题
- 未设置错题存储容器,无法实现结束后统一输出答错内容的功能
完整可运行代码
import random import requests # 请填写你的API接口地址 url = "" # 拉取全量题目 api_data = requests.get(url).json() all_questions = api_data['questions'] print("------ Welcome to Python quiz ------") # 抽取题目的数量,可自行修改 QUESTION_COUNT = 10 # 随机抽取指定数量不重复的题目 selected_questions = random.sample(all_questions, min(QUESTION_COUNT, len(all_questions))) def get_correct_answers(answers): res = [] for ans in answers: if ans['correct']: res.append(ans['answer']) return res def get_numeric(prompt, max_value): while True: try: res = int(input(prompt)) except ValueError: print("请输入数字作答!") continue if 0 < res < max_value: break else: print("选项不存在,请重新输入!") return res def main(): score = 0 # 存储答错的题目:格式为(题目内容, 用户选择的答案, 正确答案) wrong_questions = [] for q in selected_questions: # 输出题目 print(q['prompt']) # 输出选项 for i, a in enumerate(q['answers'], start=1): print(f"[{i}] {a['answer']}") # 获取用户答案 user_choice_idx = get_numeric("> ", len(q['answers']) + 1) user_selected = q['answers'][user_choice_idx - 1] # 判断对错 if user_selected['correct']: score += 1 print("回答正确!") else: correct_ans = ", ".join(get_correct_answers(q['answers'])) print(f"回答错误,正确答案是:{correct_ans}") # 存入错题列表 wrong_questions.append((q['prompt'], user_selected['answer'], correct_ans)) print("-"*30) # 输出总分 print(f"本次测验结束,你的得分是:{score}/{len(selected_questions)}") # 输出所有错题 if wrong_questions: print("\n===== 答错的题目汇总 =====") for idx, wrong in enumerate(wrong_questions, start=1): q, user_ans, correct_ans = wrong print(f"{idx}. 题目:{q}") print(f" 你的答案:{user_ans}") print(f" 正确答案:{correct_ans}\n") if __name__ == '__main__': main()
功能说明
- 完全适配你提供的API返回结构,修复了KeyError报错问题
- 默认随机抽取10道不重复题目,可通过修改
QUESTION_COUNT变量调整题量 - 测验结束后会自动汇总所有答错的题目,统一展示原题、用户作答、正确答案
内容的提问来源于stack exchange,提问作者Kevin R
相关产品推荐
相关产品推荐

