Python中的数字阶乘

问题描述

def fact(n):
    if n<0:
        return 0
    if (n==0 or n==1):
        return 1
    else:
        n * fact(n-1)

n = int(input("Enter a number"))
fact(n)

我不知道为什么给我TypeError:*:'int'和'nonetype'不受支持的操作数类型

解决方法

您无法从递归案例中返回值:

    else:
        n * fact(n-1)

您需要

    else:
        return n * fact(n-1)

默认返回值为None,因此您最终尝试在自下而上的第二个上方的每个级别上将None乘以n

例如,当您尝试使用fact(3)时,就会重复出现...

3 * fact(2)
  2 * fact(1)
    fact(1) is 1 ... return that ...
  2 * 1 is 2 ... but you then return None ...
3 * None ... is illegal
,

我相信你的意思

return n * fact(n-1)