简体   繁体   English

为什么此递归求和函数返回None?

[英]Why does this recursive summation function return None?

def recursiveadd(x,sum1):
    if x > 0:
        sum1 += x
        recursiveadd(x-1,sum1)
    else:
        return sum1

print recursiveadd(100,0)

Inserting a "print sum1" after the addition shows that sum1 is being increased, so I don't understand why the function returns None. 在添加之后插入“ print sum1”表明sum1正在增加,所以我不明白为什么函数返回None。 The only thing I can think of is that sum1 is somehow being reset to 0 before being returned, but I have no idea why that would be. 我唯一能想到的是sum1在返回之前以某种方式被重置为0,但是我不知道为什么会这样。

You need to write 你需要写

def recursiveadd(x,sum1):
    if x > 0:
        sum1 += x
        return recursiveadd(x-1,sum1)
    else:
        return sum1

print recursiveadd(100,0)
In [52]: def rec(x, sum = None):
if sum == None:
    sum = 0
if x > 0:
    sum += x
    return rec(x - 1, sum)
else:          
    return sum

....: ....:

In [53]: rec(100)
Out[53]: 5050

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM