递归函数 - 阶乘

Recursive Functions - Factorial

我对递归函数完全陌生,并尝试创建一个函数来计算 n 的阶乘。在我的示例中,我假设 n > 0.

def myfactorial(n):
    if (n - 1) > 0:                       # Check if n - 1 is > 0
       return ( n * myfactorial(n - 1) )  # Then multiply current n with myfactorial(n - 1)
    else:
        return                            # If condition is false, then stop function

但是,第 return ( n * myfactorial(n - 1) ).

行的错误 unsupported operand type(s) for *: 'int' and 'NoneType'

w3resource.com

查看解决方案时
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

他们在声明中使用了与我相同的return想法。

谁能告诉我我的方法有什么问题(顺便说一句,我故意将 if 语句设计为 n-1 > 0,但它也必须与此语句一起使用)?

非常感谢您的帮助!

returnreturn None是一样的效果。

当您执行 myfactorial(1) 时,您 return None。使用 myfactorial(2),您执行 2 * myfactorial(1),相当于 2 * None,这会触发错误:

unsupported operand type(s) for *: 'int' and 'NoneType'

这就是为什么你必须在你的 else 分支中写 return 1