Adding through recursion

Ben Finney bignose+hates-spam at benfinney.id.au
Fri Nov 18 22:36:19 CET 2005


martin.clausen at gmail.com <martin.clausen at gmail.com> wrote:
> def add(x, y):
>     if x == 0:
>         print y
>         return y
>     else:
>         x -= 1
>         y += 1
>         add(x, y)

To add to the other good advice in this thread:

This is just one of many reasons why I advocate always having a
*single* return statement, at the *end* of the function. I usually
start out writing my function setting a default return value, and the
return statement immediately below.

In your case, the default return value is None, so let's make that
explicit.

    def recursive_add(x, y):
        result = None
        return result

Then, the rest of the function's responsibility is about changing that
default value if necessary.

    def recursive_add(x, y):
        result = None
        if x == 0:
            print y
            result = y
        else:
            x -= 1
            y += 1
            recursive_add(x, y)
        return result

With this structure, it becomes quickly obvious what's gone wrong: one
of the branches is not changing the default return value.

    def recursive_add(x, y):
        if x == 0:
            print y
            result = y
        else:
            x -= 1
            y += 1
            result = recursive_add(x, y)
        return result

I find this much less error-prone than hiding return statements in
branches throughout the function; if the only return statement is at
the very end of the function, it becomes much easier to read.

-- 
 \        "If you go to a costume party at your boss's house, wouldn't |
  `\     you think a good costume would be to dress up like the boss's |
_o__)                       wife? Trust me, it's not."  -- Jack Handey |
Ben Finney



More information about the Python-list mailing list