Python问答校验程序开发:多输入存储调取与列表配对遍历问题求助
现有代码问题
- 嵌套循环逻辑错误:每道题会遍历全部答案,重复输出多次判断结果,无法实现一题对应一答的匹配需求
- 条件判断语法错误:判断语句错误将内置函数
input与整个答案列表做对比,而非用户输入的内容和对应答案对比 - 大小写匹配逻辑缺失:用户输入被转为小写,但标准答案为大小写混合格式,即使输入内容正确也会判定为错误
实现方案
双列表思路修正方法
你原有的双列表存储思路可以通过Python内置zip()函数实现同步遍历,直接配对对应位置的题目和答案,不需要嵌套循环。修正后代码如下:
question_list = ['日本的首都是什么?: ', '美国的首都是什么?: '] answer_list = ['东京', '华盛顿'] def return_question(): # zip函数会按位置同步取出两个列表的元素 for question, correct_answer in zip(question_list, answer_list): input_answer = input(question).strip() # 统一转为小写比对,避免大小写干扰 if input_answer.lower() == correct_answer.lower(): print('回答正确') else: print(f'回答错误,正确答案是:{correct_answer}') return_question()
更优实现方案
双列表存储的问题是后续新增题目时,容易出现题目、答案顺序错位的问题,维护成本高。更推荐用字典存储题目和答案的映射关系,如果后续需要扩展题型、分值等属性,也可以用列表嵌套字典的形式,灵活性更高。
以下是支持用户自主录入题目、自动判分统计的完整实现:
# 用字典存储题库,键为题目,值为标准答案 question_bank = {} def add_question(): """录入题目和对应答案到题库""" while True: question = input("请输入题目(输入q结束录入):").strip() if question.lower() == 'q': break answer = input("请输入该题对应的答案:").strip() question_bank[question] = answer print("题目录入成功\n") def start_exam(): """启动答题流程,自动出题判分""" if not question_bank: print("当前题库为空,请先录入题目") return correct_num = 0 total_num = len(question_bank) for question, correct_ans in question_bank.items(): user_ans = input(f"\n{question}:").strip() if user_ans.lower() == correct_ans.lower(): print("回答正确") correct_num += 1 else: print(f"回答错误,正确答案为:{correct_ans}") print(f"\n答题结束,总题数:{total_num},答对题数:{correct_num},正确率:{correct_num/total_num*100:.1f}%") # 执行逻辑:先录入题目再启动答题 add_question() start_exam()
内容的提问来源于stack exchange,提问作者paulnewbie34
相关产品推荐
相关产品推荐

