Breaking out of nested loop

Jay O'Connor joconnor at cybermesa.com
Tue Feb 27 18:20:22 CET 2001


Dan wrote:

> How might one go about breaking out of a multi level loop?
>
> For instance, the following code will go into an endless loop.
>
> while(1):
>     while(1):
>         break
>
> Is there a statement that one can use to break out of multiple levels
> of loop control?  I really hate to start littering my code with flag
> variables and if statements.

Factor the inner loop into a seperate function that returns whether or
not to keep looping and have that the test condition for the outer loop

Example:
>>> x = 10
>>> def secondLoop ():
    global x
    x = x -1
    return x == 1

>>> while not secondLoop():
    print x

9
8
7
6
5
4
3
2
>>>

I find factor nested loops into seperate functions easier to read, as
well, because it allows you to focus on different parts of the logic as
you need to.  I don't have to look at secondLoop()s logic if I just want
to deal with the outer loop.  Simularly, I don't have to be distracted by
the outer loop if I have a bug in the code inside secondLoop()

Take care,
Jay




More information about the Python-list mailing list