return command in a function.

Peter Hansen peter at engcorp.com
Wed Sep 26 23:28:56 EDT 2001


Brian Lee wrote:
> 
> Hi all! I'm newbie at programming and especially Python langauge.
> 
> What do you think when someone put return, break or continue command
> in half of a function. I think that commands are like ``goto'' It is very
> confused for me to understand big code because such commands
> jump un-excepted line.
> 
> What do you think about this and how can get be avoid of using
> such commands? Any advice?

A return statement in the middle of a function is sometimes
considered poor style.  Depending on the function it can actually
be good style, too, unless you're a purist.  With very short
functions, such as one with a simple if that selects one of
two return statements, any other pattern might be even harder
to understand.  Contrast these two:

def odd(intval):
    if intval & 1:
        return 1
    else:
        return 0

def odd(intval):
    if intval & 1:
        result = 1
    else: 
        result = 0
    return result

The first is probably the better choice in this simple example.

Break and continue statements really *have* to come in the
middle of a function, or they're of no real use.  These
statements are what the programming community invented to
*avoid* goto statements, in a sense.  They should be used
where appropriate, which is any time the flow of control
needs to take a quick change of direction either back to
the beginning of a loop, or out of a loop entirely.  If
you didn't use them, you'd spend a lot of time writing
code to avoid them and the result would be less clear.

If you are getting confused by "big code", it could be 
the fault of the original programmer.  Code that is so
large it can't be understood easily even with well-structured
statements like break and continue could be poorly written
code, so you shouldn't feel bad about not understanding it.
Some rules of thumb include things like "no function should
be larger than can fit in one screen".

On the other hand, you need to learn to read code that
has "jumps to unexpected lines" since that's likely to 
occur frequently in most interesting programs...

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list