Python随机数学测验程序问题排查:答案不识别且重复出题
Python数学测验程序问题排查与修复
嘿,我帮你梳理下这两个问题的根源和修复方法,都是新手写这类程序常踩的坑~
一、答案正确却不被识别的问题
这个几乎百分百是输入类型不匹配导致的!你用input()获取的用户输入是字符串类型,但数学题的正确答案是整数/数值类型,直接拿字符串和整数比,肯定永远不相等呀。
举个反例,你可能写了这样的错误代码:
correct_answer = 15 user_answer = input("Enter your answer: ") if user_answer == correct_answer: # 这里"15"和15比较,结果是False print("Correct!")
修复方法
把用户输入转换成整数类型,同时加上异常处理,防止用户输入非数字内容:
try: user_answer = int(input("Enter your answer: ")) if user_answer == correct_answer: print("Nice work, that's spot on!") else: print(f"Oops, wrong one. The right answer is {correct_answer}") except ValueError: print("Hey, please enter a valid number!")
二、题目持续重复的问题
题目重复是因为你没记录已经出过的题目,每次随机生成时很容易撞车。咱们可以用一个集合来存已经出过的题目特征,生成新题时先检查有没有出过,没出过再用。
修复思路&代码片段
# 用集合存储已出的题目(元组可哈希,适合当集合元素) used_questions = set() def generate_unique_question(): while True: num1 = random.randint(1, 20) num2 = random.randint(1, 20) # 随机选运算符 op = random.choice([operator.add, operator.sub, operator.mul]) # 用(num1, num2, 运算符名称)作为题目标识 question_key = (num1, num2, op.__name__) if question_key not in used_questions: used_questions.add(question_key) return num1, num2, op
这样每次生成的题目都是之前没出过的,直到你设置的总题数完成或者所有可能的题目都出完。
给你补个完整的修复后代码
我把这些修复整合到了完整程序里,还加了分数统计和避免减法出现负数的细节:
import random import operator name = input("Type your name: ") print(f"Hi {name}! This math quiz will test your basic math ability.") print("Please answer each question with a number. Let's start!\n") used_questions = set() score = 0 total_questions = 5 # 可以自己调整总题数 def generate_unique_question(): while True: num1 = random.randint(1, 20) num2 = random.randint(1, 20) # 随机选运算符,减法时保证被减数大于等于减数,避免负数答案 op_choice = random.choice([operator.add, operator.sub, operator.mul]) if op_choice == operator.sub: num1, num2 = max(num1, num2), min(num1, num2) op = operator.sub else: op = op_choice question_key = (num1, num2, op.__name__) if question_key not in used_questions: used_questions.add(question_key) return num1, num2, op for _ in range(total_questions): num1, num2, op = generate_unique_question() # 把运算符转换成符号,方便显示题目 op_symbol = {operator.add: '+', operator.sub: '-', operator.mul: '*'}[op] print(f"What is {num1} {op_symbol} {num2}?") try: user_answer = int(input("> ")) correct_answer = op(num1, num2) if user_answer == correct_answer: print("Correct!\n") score += 1 else: print(f"Wrong answer. The correct one is {correct_answer}\n") except ValueError: print("Please enter a valid integer!\n") print(f"Quiz over! Your score is {score}/{total_questions}")
内容的提问来源于stack exchange,提问作者user9126689
相关产品推荐
相关产品推荐

