Several ideas on how Python interrupts multiple loops

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.