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

Python3数学答题游戏开发问题:timer函数无法返回分数求排查

问题分析与修复方案

你的timer函数没法正确返回分数,主要有几个核心遗漏点,我帮你逐一拆解:

1. 答题判断逻辑未完成,结果传递错误

你的top()函数里if pansw ...的代码没写完,而且输入的pansw是字符串类型,直接和整数tansw比较会永远不相等——这会导致soru()无法返回正确的答题结果(True/False),进而让timer()里的answ == True判断彻底失效,最终一直返回0。

2. 可能未接收timer函数的返回值

就算timer函数逻辑正确,如果你只是直接调用timer()而没有把返回值赋值给变量(比如current_score = timer()),那你根本拿不到这个分数结果。

修正后的完整代码片段

import random, time
n = 2
a = 0

def timer():
    stime = time.time()
    answ = soru()
    score = round(time.time() - stime, 2)
    print(score, "ara zaman")
    if answ:  # 直接判断布尔值更简洁
        return score
    else:
        return 0

def soru():
    return top()

def top():
    n1 = random.randint(1, n*5)
    n2 = random.randint(1, n*5)
    tansw = n1 + n2
    print(f"{n1}+{n2}=?")  # 用f-string简化字符串拼接
    try:
        pansw = int(input("--->"))  # 将输入转为整数,同时捕获非数字输入异常
        return pansw == tansw
    except ValueError:
        print("请输入有效的数字!")
        return False

# 调用timer并接收返回的分数
final_score = timer()
print(f"最终得分:{final_score}")

关键修复点解释

  • 在top()函数中,我们把输入的字符串转为整数int(input(...)),同时用try-except处理用户输入非数字的情况,避免程序直接崩溃。
  • 完善了判断逻辑,直接返回pansw == tansw的布尔结果,确保soru()能正确给timer()传递答题是否正确的信号。
  • 增加了调用示例,用final_score = timer()接收返回值,这样你就能拿到分数进行后续的累加或展示操作了。

内容的提问来源于stack exchange,提问作者Barış Kılınç

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:31:42