Python - `break` out of all loops
61,017
Solution 1
You can raise an exception
try:
for a in range(5):
for b in range(5):
if a==b==3:
raise StopIteration
print b
except StopIteration: pass
Solution 2
why not use a generator expression:
def my_iterator()
for i in range(1, 1001):
for i2 in range(i, 1001):
for i3 in range(i2, 1001):
yield i,i2,i3
for i,i2,i3 in my_iterator():
if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000:
print i*i2*i3
break
Solution 3
Not sure if this the cleanest way possible to do it but you could do a bool check at the top of every loop.
do_loop = True
for i in range(1, 1001):
if not do_loop:
break
for i2 in range(i, 1001):
# [Loop code here]
# set do_loop to False to break parent loops
Author by
Vader
Updated on January 24, 2020Comments
-
Vader over 4 years
I am using multiple nested
for
loops. In the last loop there is anif
statement. When evaluated toTrue
all thefor
loops should stop, but that does not happen. It onlybreak
s out of the innermostfor
loop, and than it keeps on going. I need all loops to come to a stop if thebreak
statement is encountered.My code:
for i in range(1, 1001): for i2 in range(i, 1001): for i3 in range(i2, 1001): if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000: print i*i2*i3 break
-
Vader over 10 yearsI want to avoid adding more checks and loops. The current code is quite inefficient as it is.
-
CodeManX over 10 yearsSeems a bit odd to use an exception in this particular case (and doesn't look so nice), since the code should really be put into its own function - and
return
will then work. -
lweingart over 7 yearsIn some cases one would still have to execute some lines of code after the loops, so I will go for the try except solution
-
Admin over 2 yearsUnderrated answer. Perfect