How to label loops?

Quinn Dunkan quinn at lira.ugcs.caltech.edu
Mon Feb 12 01:07:42 CET 2001


On Sun, 11 Feb 2001 19:35:53 GMT, Steffen Ries <steffen.ries at sympatico.ca>
wrote:
>> while 1:                # first loop
>>     while 1:            # second loop 
>>         break
>> 
>> 
>> this break breaks only out of the first loop, but what, if i want to
>> break out of the first loop, while i´m in the second one?
>
>one way is to use control variables, e.g.:
>
>outer_active = 1
>inner_active = 1
>while outer_active:
>    while inner_active:
>       outer_active = 0
>       break
>
>another way would be to use exceptions, e.g.:
>
>try:
>    while 1:
>        while 1:
>            raise Exception, "broken loop"
>except Exception:
>    pass

That will catch and ignore all sorts of things you don't want to ignore, like
OSError and MemoryError.  If you must (ab)use an exception for control flow,
you should probably use a string:

try:
    while 1:
        while 1:
            raise 'outer loop'
except 'outer loop': # just don't misspell this :)
    pass

I've found that I rarely need to break from two levels at once, and when I
think I do, often python's (unique) 'while x: ... else:' construct will do the
trick.  But if you find yourself doing complicated 'while x: xxx else: break'
to break from the outer loop if the inner one isn't, and then break from the
inner loop if you want to *not* break the outer loop, which is only a nominal
loop since it has 'break' at the end and you use continue... well, what you
really want here is 'goto' :)

As in "go back to fortran" :)



More information about the Python-list mailing list