Adding through recursion

Gerard Flanagan grflanagan at yahoo.co.uk
Fri Nov 18 09:39:10 EST 2005


martin.clausen at gmail.com wrote:

> I still don't get it. I tried to test with x = 0 and found that to
> work. How come since the value of y is right and it is printed right it
> "turns into" None when returned by the return statement ?


Martin,

-a function should either return something or not.  Your function has
two exit points, one explicitly returns a value, one doesn't (and so
defaults to returning None).

- trace through the function with pencil and paper for small values of
x and y

def add(x, y):
    if x:
        x -= 1
        y += 1
        add(x,y)
    else:
        print y


def ADD(x, y):
    if x:
        x -= 1
        y += 1
        return ADD(x,y)
    else:
        return y

>>>add(5,6)
11
>>>ADD(5,6)
11

>>>z = add(5,6)
11
>>>print z
None
>>>z = ADD(5,6)
>>>print z
11


Gerard




More information about the Python-list mailing list