How to label loops?
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>
>> while 1: # first loop
>> while 1: # second loop
>> 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 inner_active:
> outer_active = 0
>another way would be to use exceptions, e.g.:
> while 1:
> while 1:
> raise Exception, "broken loop"
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:
raise 'outer loop'
except 'outer loop': # just don't misspell this :)
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