函数递归类型不同
>>> def f(x):if x-2 > 0 :
result = f(x-1)+f(x-2)
else:
return 1
>>> f(20)
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
f(20)
File "<pyshell#36>", line 3, in f
result = f(x-1)+f(x-2)
File "<pyshell#36>", line 3, in f
result = f(x-1)+f(x-2)
File "<pyshell#36>", line 3, in f
result = f(x-1)+f(x-2)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
如上,问题在哪? 缺了返回值,加个return就好了
def f(x):
if x - 2 > 0:
result = f(x - 1) + f(x - 2)
return result
else:
return 1
print(f(20)) if分支满足条件后进入,没有返回值。
页:
[1]