胡传骏 发表于 2020-9-4 11:06:17

函数递归类型不同

>>> 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'

如上,问题在哪?

疾风怪盗 发表于 2020-9-4 12:57:25

缺了返回值,加个return就好了
def f(x):
    if x - 2 > 0:
      result = f(x - 1) + f(x - 2)
      return result
    else:
      return 1

print(f(20))

heidern0612 发表于 2020-9-4 14:43:30

if分支满足条件后进入,没有返回值。
页: [1]
查看完整版本: 函数递归类型不同