我写了这段代码,我有一个返回问题。你知道吗
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n - 1)
result = n * recurse
return result
factorial(3)
当我运行它的时候,我有一个输出:
Process finished with exit code 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
我的问题是-为什么当我试着用return运行它时,我什么也看不到,第二个带print的代码呢?你知道吗
也许我的问题是愚蠢的,但人类从错误中学习
在第二个版本中,当
n == 0
打印1
时不返回任何内容。结果,函数返回None
,这是不能相乘的。你知道吗第一个版本是正确的,但如果要查看结果,必须编写:
作为参考,这是您的全部代码。你知道吗
相关问题 更多 >
编程相关推荐