How python jumps out of multiple loops
Editor to share with you python how to jump out of multiple cycles, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!
Jump out of multiple cycles
In fact, Python's standard syntax does not support jumping out of multiple loops, so you can only use some techniques, such as writing functions, using Cartesian products, and debugging.
Of course, the most common idea is to use variable labeling.
Def f (): flag = 0 for i in range (10): for j in range (I): if itemj > 5: print iPowerj flag = 1 breakif flag = = 1: breakif _ _ name__ = = "_ _ main__": F ()
Write as a function
In Python, the function stops when it runs to return, so you can take advantage of this feature to write the function as a function, terminating multiple loops, such as
Def work (): for i in range (10): for j in range (10): if iMagj > 5: return iMagnejprint work ()
Using Cartesian product
The idea of this approach is that since I can jump out of a single loop, I will rewrite a multiple loop to a single loop, which can take advantage of the Cartesian product function product in itertools, such as
From itertools import productfor iMagol j in product (range (10), range (10)): if iMagj > 5: print iMagol j break
Using debug mode
The Cartesian product is ingenious and concise, but it can only be used when the set of each loop is independent. If each loop is closely related to the previous layer, this technique cannot be used. At this point, you can write it as a function in the first way, and you can also take advantage of debug mode. This takes advantage of the principle of quitting as soon as an error is reported in debug mode, which disguises an error.
Class Found (Exception): passtry: for i in range (10): for j in range (I): # the second loop is about if I + j > 5: raise Foundexcept Found: print I, j is all the content of the article "how to get out of multiple cycles by python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!