Adding through recursion

bonono at gmail.com bonono at gmail.com
Fri Nov 18 18:22:12 EST 2005


Ben Finney wrote:
> 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.

I don't see this as clearer than multiple return. But then it I believe
it is really preference or style, rather than obvious
advantage/disadvantage.

Interestingly, this kind of error is easy to spot by the compiler in C.




More information about the Python-list mailing list