Adding through recursion
Peter Tillotson
none at no.chance
Fri Nov 18 08:55:50 EST 2005
basically the other two points :-)
you create a string of add functions
add(2,4)--add(1,5)--add(0,6)
only in the last ( add(0,6) ) explicitly returns y, in the else of
add(1,5) you ignor it. If you want the starting add to return something
sensible you need to find a way to pass it back up the function chain.
not tested
def add(x, y):
if x == 0:
sum = y
print sum
else:
x -= 1
y += 1
sum = add(x, y)
return sum
print add(2, 4)
martin.clausen at gmail.com wrote:
> There is problaly a really simple answer to this, but why does this
> function print the correct result but return "None":
>
> def add(x, y):
> if x == 0:
> print y
> return y
> else:
> x -= 1
> y += 1
> add(x, y)
>
> print add(2, 4)
>
> result:
> 6
> None
>
> Martin
>
More information about the Python-list
mailing list