In Python, how does one use break to jump out of multiple layers of loops?

Source: Internet
Author: User
Forainxrange (10): forbinxrange (20): ifsomething (a, B): # Breaktheinnerloop... breakelse: # Continueiftheinnerloopwasntbroken.
For a in xrange (10): for B in xrange (20): if something (a, B): # Break the inner loop... break else: # Continue if the inner loop wasn' t broken. continue # Inner loop was broken, break the outer. break
Reply: I can't help but say something ...... You never read official documents when learning python. Did you just follow the Chinese tutorial of XX?

The Python loop body has its own else branch!
The Python loop body has its own else branch!
The Python loop body has its own else branch!

Not only if, but both while and for have else branches. The trigger condition for the else branch of the loop body is that the loop ends normally.. If a break exists in the loop, else is not executed. Therefore, the logic is: if the break in the loop does not trigger else, the break in the next outer loop is executed; if it ends normally, the continue in the else branch is executed, jump directly to the next round of the outer loop and skip the second break.

But Nima is ugly ...... Is it possible to make a Boolean ......

--------

In fact, the correct posture should be to wrap up a function and then use return ...... After an exception is thrown, The else clause for and while is used for loop post-processing. The clause is executed only when the loop ends normally.

In the example above, setting a flag variable makes the code more intuitive.

It's hard to say which method is better. I like else branch very much.

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.