There are several ways to break out of several nested loops.
It:
1) use break-continue
for x in xrange(10): for y in xrange(10): print x*y if x*y > 50: break else: continue
2) use return
def foo(): for x in range(10): for y in range(10): print x*y if x*y > 50: return foo()
3) use a special exception
class BreakIt(Exception): pass try: for x in range(10): for y in range(10): print x*y if x*y > 50: raise BreakIt except BreakIt: pass
I thought there might be another way to do this. It is through the exception that StopIteration is sent directly to the external loop. I wrote this code
it = iter(range(10)) for i in it: for j in range(10): if i*j == 20: raise StopIteration
Unfortunately, StopIteration was not caught by any for loop, and this code caused an ugly Traceback. I think because StopIteration was not sent from inside iterator it . (what I think, I'm not sure about that).
Is there a way I can send StopIteration to an outer loop?
Thanks!
ovgolovin
source share