【发布时间】:2012-05-10 05:06:16
【问题描述】:
def recursiveadd(x,sum1):
if x > 0:
sum1 += x
recursiveadd(x-1,sum1)
else:
return sum1
print recursiveadd(100,0)
在加法后插入“print sum1”表明sum1正在增加,所以我不明白为什么函数返回None。我唯一能想到的是 sum1 在返回之前以某种方式被重置为 0,但我不知道为什么会这样。
【问题讨论】:
-
跟踪您的代码并查看返回的内容,重点是returned。
-
注意尾递归会炸毁python中的堆栈。
-
@MattFenwick: 你可以call it without blowing up the stack