[Tutor] Multiple exits in a function...

Daniel Ehrenberg littledanehren at yahoo.com
Fri Oct 24 15:28:45 EDT 2003


> Hi Alan,
> 
> 
> Wait, wait, I think we're talking about something
> else.
> 
> Let's say we're writing a function that searches a
> list for an even
> number.  If it can find it, the function will return
> it.  Otherwise, it'll
> return -1.
> 
> Here's one way to write it:
> 
> ###
> def findEven(L):
>     """Returns an even number out of list L.  If no
> such number exists,
>     returns -1."""
>     for x in L:
>         if x % 2 == 0:
>             return x
>     return -1
> ###
> 
> This is a function with multiple "exits" out of the
> function: we get out
> either through the first "return", or the "second"
> return.
> 
> 
> There's another way of writing this so that there's
> only one 'return' out
> of the function:
> 
> ###
> def findEven(L):
>     """Returns an even number out of list L.  If no
> such number exists,
>     returns -1."""
>     result = -1
>     for x in L:
>         if x % 2 == 0:
>             result = x
>     return result
> ###
> 
> (The behavior of both functions is not quite
> equivalent.  That's why the
> docstring doesn't say anything about returning the
> 'first' even number it
> encounters.)
> 
> 
> Talk to you later!

I really don't see what's wrong with multiple returns,
especially in a simple function like this. To me, the
first one is more clear. For this function in
particular, wouldn't the first one terminate first
because it doesn't have to go through the entire list?
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com



More information about the Tutor mailing list