Breaking out of nested loop

Jay O'Connor joconnor at
Tue Feb 27 12:20:22 EST 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

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

>>> while not secondLoop():
    print x


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,

More information about the Python-list mailing list