[Tutor] Multiple exits in a function...

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Oct 24 13:51:02 EDT 2003



On Fri, 24 Oct 2003, Alan Trautman wrote:

> In this case they should call the same exit function. Especially if you
> do any cleanup or logging. If they use different functions for each
> exit, do you really want to maintain two exit functions? Or as happens
> more often you forget one and that's the one your users will use causing
> a problem that will be very hard to troubleshoot.

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!




More information about the Tutor mailing list