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

Python递归函数返回None问题:累加求和函数异常排查

问题原因分析

你的递归函数在number > 0的分支里,调用了递归函数ComputeMath(number-1, result),但没有返回这个调用的结果。Python中如果函数没有显式写return语句,默认会返回None。所以当你调用ComputeMath(5,0)时,虽然最底层的else分支正确返回了累加结果,但上层的递归调用没有把这个结果传递回来,最终整个函数返回的就是None。

修正后的代码
def ComputeMath(number, result):
    if number > 0:
        result = number + result
        print('if', result)
        # 返回递归调用的结果,传递给上层函数
        return ComputeMath(number-1, result)
    else:
        print("else", result)
        return result

output = ComputeMath(5,0)
print(output)
验证说明

修正后,每一层递归都会把下层返回的累加结果传递回上层,最终ComputeMath(5,0)会返回正确的累加和15,print(output)就能输出预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:50:40