Python:返回不行

时间:2018-01-14 02:55:21

标签: python factorial

我写了这段代码,我遇到了返回问题。

def factorial(n):
  if n == 0:
    return 1
  else:
    recurse = factorial(n - 1)
    result = n * recurse
    return result
factorial(3)

当我运行它时,我有输出:

  

处理完成,退出代码为0

就是这样,但是当我尝试打印时,我还有一些额外的东西:

代码:

def factorial(n):
  if n == 0:
    print ("1")
  else:
    recurse = factorial(n - 1)
    result = n * recurse
    print(result)
factorial(3)

输出:

Traceback (most recent call last):
1
Traceback (most recent call last):
  File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 16, in <module>
    factorial(3)
  File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 13, in factorial
    recurse = factorial(n - 1)
  File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 13, in factorial
    recurse = factorial(n - 1)
  File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 14, in factorial
    result = n * recurse
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

Process finished with exit code 1

我的问题是 - 为什么当我尝试使用返回运行时,我看不到任何内容以及带有打印的第二个代码呢?

也许我的问题是愚蠢的,但人类会从错误中吸取教训

1 个答案:

答案 0 :(得分:2)

在您的第二个版本中,n == 0时您不会返回任何内容,只需打印1即可。结果,函数返回None,这是你无法乘法的。

第一个版本是正确的,但如果你想看到你必须写的结果:

print(factorial(3))

供参考,这是您的完整代码。

def factorial(n):
  if n == 0:
    return 1
  else:
    recurse = factorial(n - 1)
    result = n * recurse
    return result

print(factorial(3))