No matter what programming language you’re in, you might have a need to break out of a loop, such as when enumerations are terminated when a number meets a condition. It’s easy to break out of a single loop, like
for i in range(10) :if i > 5:
print (i)
break
Copy the code
However, sometimes we need to break out of multiple loops, whereas a break can only break out of one loop, for example
for i in range(10) :for j in range(10) :if i+j > 5:
print (i,j)
break
Copy the code
Instead of finding a set of I +j > 5 and stopping, this code finds 10 groups in a row, because the break only breaks out of the loop for j in range(10). So how do you get out of weight? Take notes here.
2. Break out of multiple cycles
In fact, Python’s standard syntax doesn’t allow for breaking out of multiple loops, so you can only use a few tricks, along the lines of: write functions, use Cartesian products, and use debugging.
The most common idea, of course, is to use variable notation
def f() :
flag = 0
for i in range(10) :for j in range(i):
if i+j>5:
print (i,j)
flag = 1
break
if flag == 1:
break
if __name__ == "__main__":
f()
Copy the code
Write function
In Python, functions stop at the return line, so you can use this feature to write functions as functions to terminate multiple loops, for example
def work() :
for i in range(10) :for j in range(10) :if i+j > 5:
return i,j
print (work())
Copy the code
Using cartesian product
The idea is, since I can get out of a single loop, I’ll rewrite multiple loops as a single loop, using the Cartesian product function in Itertools, for example
"Have a problem and no one to answer it? We have created a Python learning group: 531509025 to find people who can help each other. We also have great video tutorials and PDF ebooks. ' ' '
from itertools import product
for i,j in product(range(10), range(10)) :if i+j > 5:
print (i,j)
break
Copy the code
Use debug mode
The Cartesian product is clever and neat, but it can only be used if the set of each cycle is independent, not if each cycle is closely related to the previous one. You can use the first method, writing it as a function, or you can use debug mode. This makes use of the debug mode principle of exiting as soon as an error occurs. It disguises an error.
class Found(Exception) :
pass
try:
for i in range(10) :for j in range(i): # The second loop is related to the first loop
if i + j > 5:
raise Found
except Found:
print (i, j)
Copy the code