Common methods
II. Jump out of multiple loops
In fact, Python's standard syntax is not to support jumping out of multiple loops, so it can only take advantage of some techniques, the general idea is: Write functions, using Cartesian product, using debugging.
Write function
In Python, the function runs to return and stops, so you can use this feature to write functions to terminate multiple loops, such as
DefWork(): For I in range: for J in range: if I+j C16>> 5: return i, JPrint work()
Using Cartesian product
The idea of this approach is that since you can jump out of a single loop, I'll rewrite the multiple loops into a single loop, which can take advantage of the Cartesian product function product in Itertools, such as
from itertools import Productfor i,j in product (Range10 ( 10) ) : if i+j > 5: print i,j break
Using debug mode
The Cartesian product is very clever and concise, but it can only be used for each cycle of the set is independent of the situation, if each layer of cycle is closely related to the previous layer, it is not possible to use this technique. In this case, you can use the first method to write it as a function, and you can also take advantage of debug mode. This uses the debug mode, as long as an error occurs on the exit principle, it disguised a mistake out.
ClassFound(Exception):Passtry: for i in range10 for j in range: #第二重循环跟第一重有关 if i + J > 5: raise foundexcept found: print i
Several ways Python interrupts multiple loops