Breaking out of nested loop
joconnor at cybermesa.com
Tue Feb 27 18:20:22 CET 2001
> How might one go about breaking out of a multi level loop?
> For instance, the following code will go into an endless loop.
> 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 ():
x = x -1
return x == 1
>>> while not secondLoop():
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()
More information about the Python-list