I use the following method to break the double loop in Python.
for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break
Is there a better way to break the double loop?
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
You can break all loops with else and continue . The code with explanation is as follows. When the inner loop ends normally without break , continue in the else clause is executed. This continue is for the outer loop, and skips break in the outer loop and continues to the next cycle.
Probably not what you are hoping for, but usually you would want to have a break
after setting find
to True
for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True break # <-- break here too if find: break
Another way is to use a generator expression to squash the for
into a single loop
for word1, word2 in ((w1, w2) for w1 in buf1 for w2 in buf2): ... if res == res1: print "BINGO " + word1 + ":" + word2 break
You may also consider using itertools.product
from itertools import product for word1, word2 in product(buf1, buf2): ... if res == res1: print "BINGO " + word1 + ":" + word2 break
The recommended way in Python for breaking nested loops is... Exception
class Found(Exception): pass try: for i in range(100): for j in range(1000): for k in range(10000): if i + j + k == 777: raise Found except Found: print i, j, k
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With