Given the following code (that doesn\'t work):
while True:
#snip: print out current state
while True:
ok = get_input(\"Is this ok? (y/n)\")
Since this question has become a standard question for breaking into a particular loop, I would like to give my answer with example using Exception
.
Although there exists no label named breaking of loop in multipally looped construct, we can make use of User-defined Exceptions to break into a particular loop of our choice. Consider the following example where let us print all numbers upto 4 digits in base-6 numbering system:
class BreakLoop(Exception):
def __init__(self, counter):
Exception.__init__(self, 'Exception 1')
self.counter = counter
for counter1 in range(6): # Make it 1000
try:
thousand = counter1 * 1000
for counter2 in range(6): # Make it 100
try:
hundred = counter2 * 100
for counter3 in range(6): # Make it 10
try:
ten = counter3 * 10
for counter4 in range(6):
try:
unit = counter4
value = thousand + hundred + ten + unit
if unit == 4 :
raise BreakLoop(4) # Don't break from loop
if ten == 30:
raise BreakLoop(3) # Break into loop 3
if hundred == 500:
raise BreakLoop(2) # Break into loop 2
if thousand == 2000:
raise BreakLoop(1) # Break into loop 1
print('{:04d}'.format(value))
except BreakLoop as bl:
if bl.counter != 4:
raise bl
except BreakLoop as bl:
if bl.counter != 3:
raise bl
except BreakLoop as bl:
if bl.counter != 2:
raise bl
except BreakLoop as bl:
pass
When we print the output, we will never get any value whose unit place is with 4. In that case, we don't break from any loop as BreakLoop(4)
is raised and caught in same loop. Similarly, whenever ten place is having 3, we break into third loop using BreakLoop(3)
. Whenever hundred place is having 5, we break into second loop using BreakLoop(2)
and whenver the thousand place is having 2, we break into first loop using BreakLoop(1)
.
In short, raise your Exception (in-built or user defined) in the inner loops, and catch it in the loop from where you want to resume your control to. If you want to break from all loops, catch the Exception outside all the loops. (I have not shown this case in example).