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

Python递归函数实现阶乘时报错,代码存在什么问题?

代码错误分析
  • 递归终止条件返回值错误:当n==1时,你当前的代码写的是无返回值的return,实际返回的是None,执行n * fact(n-1)时会触发TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'类型错误,因为整数无法和空值做乘法运算。阶乘的递归终止条件应该返回1,因为1的阶乘结果为1。
  • 可选优化:没有覆盖n=0的边界场景,0的阶乘规定为1,可将终止条件调整为n <= 1适配该场景。
修改后可运行代码
def fact(n):
    if n <= 1:
       return 1
    else:
        return n * fact(n-1) 
d = int(input("Enter the number"))
print(fact(d))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:57:02