You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python数学答题游戏开发:答案判断错误问题排查求助

问题

需求说明:

  • 代码需生成随机等式供用户作答,num1范围为1-9,num2范围为0-10;
  • 用户初始得分为100分;
  • 用户输入x时程序终止;
  • 答错扣10分;
  • 答对加9分。

我已完成上述1-3步,但在验证用户输入答案是否正确时,即便答案正确也会被判定错误。猜测是代码未正确计算题目结果导致该问题,以下是我的代码:

import random


# set variables
score = 100  # score of user
operator = ["+", "-", "*", "/"] #operators
number_1 = random.randint(1, 9)  # this variable will be a random number between 1 and 9
number_2 = random.randint(0, 10)  # this variable will be a random number between 0 and 10


# this function prints the dashes
def dash():
    print("-" * 50)

while score >= 0 and score <= 200:
    dash()
    print("You currently hold: ", score, " points")
    print("Get more than 200 points you win, under 0 you lose")

    sign = random.choice(operator)  # chooses random operator
    real_answer = number_1,sign,number_2

    print(str(number_1) + str(sign) + str(number_2), "?")
    dash()
    print("Press x to close program")
    answer = input("Enter your guess of number: ")

    if answer == "x":
        print("Program has been terminated properly")
        break
    elif answer == real_answer:
        score = score + 9
        continue
    elif answer  != real_answer:
        score = score - 10
        continue

if score < 0:
        print("Unlucky, You lost")

elif score > 200:
    print("CONGRATULATIONS YOU WON")

问题分析与修复

你的代码核心问题有三个:

  1. 未正确计算等式结果:real_answer = number_1,sign,number_2只是创建了一个元组(比如(3, '+', 5)),并没有计算等式的实际结果,完全无法和用户输入的数字答案匹配。
  2. 随机数只初始化一次:number_1和number_2在循环外定义,导致每次循环都是同一组数字,不会生成新题目。
  3. 类型不匹配与除法漏洞:用户输入的是字符串,而正确结果是数字,类型不匹配;除法遇到0时会直接报错,且未处理小数输入的精度问题。

修正后的代码

import random


def dash():
    print("-" * 50)

score = 100
operators = ["+", "-", "*", "/"]

while 0 <= score <= 200:
    dash()
    print(f"当前得分: {score} 分")
    print("得分超过200获胜,低于0失败")
    
    # 每次循环生成新的随机数
    num1 = random.randint(1, 9)
    num2 = random.randint(0, 10)
    sign = random.choice(operators)
    
    # 计算正确答案,处理除法除零情况
    real_answer = None
    try:
        if sign == "+":
            real_answer = num1 + num2
        elif sign == "-":
            real_answer = num1 - num2
        elif sign == "*":
            real_answer = num1 * num2
        elif sign == "/":
            if num2 == 0:
                continue  # 遇到除零重新生成题目
            real_answer = round(num1 / num2, 2)  # 保留两位小数方便用户输入
    except ZeroDivisionError:
        continue
    
    print(f"{num1}{sign}{num2} = ?")
    dash()
    print("输入x终止程序")
    user_input = input("请输入你的答案: ")
    
    if user_input.lower() == "x":
        print("程序已正常终止")
        break
    
    # 处理用户输入的类型转换,避免非数字输入报错
    try:
        user_answer = float(user_input)
        # 用近似比较处理小数精度问题
        if abs(user_answer - real_answer) < 0.01:
            score += 9
            print("回答正确!加9分")
        else:
            score -= 10
            print(f"回答错误!正确答案是{real_answer},扣10分")
    except ValueError:
        print("输入无效,请输入数字或x")
        continue

if score < 0:
    print("很遗憾,你输了")
elif score > 200:
    print("恭喜你获胜!")

关键修复点说明

  • 将随机数生成移到循环内部,确保每次都有新题目。
  • 用条件分支计算每个运算符的实际结果,处理除法除零的异常情况。
  • 对用户输入做类型转换和异常捕获,避免非数字输入导致程序崩溃。
  • 用绝对值差判断答案是否正确,解决小数输入的精度匹配问题。

内容的提问来源于stack exchange,提问作者L2CBlue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 09:55:13