python递归题目_Python递归的问题?

本文探讨了一段使用装饰器的Python递归阶乘代码出现的问题。当使用特定语法调用带装饰器的递归函数时,程序会抛出错误。文章分析了问题原因,并对比了不同调用方式的效果。

import time

def outer(F):

def wrapper(x):

start = time.time()

F(x)

end = time.time()

print(end - start)

return wrapper

@outer

def func2(a):

if a == 1:

return 1

else:

return a * func2(a-1)

func2(7)

上面是一段python递归实现阶乘的代码,但是在加上装饰器之后就报错了,想请大家看下问题出在哪里?为什么调用的时候不用 @outer这种方式,而用原始的 outer(func2)(7)就没问题了?

报错如下:

[root@yang python]# python3 test.py

7.152557373046875e-07

Traceback (most recent call last):

File "test.py", line 22, in

func2(7)

File "test.py", line 6, in wrapper

F(x)

File "test.py", line 17, in func2

return a * func2(a-1)

File "test.py", line 6, in wrapper

F(x)

File "test.py", line 17, in func2

return a * func2(a-1)

File "test.py", line 6, in wrapper

F(x)

File "test.py", line 17, in func2

return a * func2(a-1)

File "test.py", line 6, in wrapper

F(x)

File "test.py", line 17, in func2

return a * func2(a-1)

File "test.py", line 6, in wrapper

F(x)

File "test.py", line 17, in func2

return a * func2(a-1)

File "test.py", line 6, in wrapper

F(x)

File "test.py", line 17, in func2

return a * func2(a-1)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值