Python (3)-loop statement: Jump out of a multilayer loop from the inner layer

Source: Internet
Author: User

Jump out of the multilayer loop: three-layer loop, the innermost layer directly jumps out 3 layers

Method One:
In Python, the function runs to return and stops, so you can use this feature to write functions as functions to terminate multiple loops

1234567891011121314 defwork():                                  #定义函数    for inrange(5):        print("i=", i)        forinrange(5):            print("--j=", j)            forinrange(5):                ifk<2:                    print("------>k=", k)                else:                    returni,j,k             print(work())

  

Method Two:
Define variables, change the state of variables, do not meet the conditions, loop out

123456789101112131415 break_flag=Falseforinrange(10):    print("爷爷层")    forin range(10):        print("爸爸层")        forinrange(10):            print("孙子层")            ifk==3:                break_flag=True                break#跳出孙子层循环,继续向下运行        ifbreak_flag==True:            break#满足条件,运行break跳出爸爸层循环,向下运行    ifbreak_flag==True:        break #满足条件,运行break跳出爷爷层循环,结束全部循环,向下运行print("keep going...")

Method Three:

While loop statement, define condition, condition change, Loop end

123456789101112131415 break_flag=Falsecount=0whilebreak_flag==False:    print("爷爷层...")    whilebreak_flag==False:        print("爸爸层...")        whilebreak_flag==False:            ifcount<5:                print("孙子层...")                count+=1            else:                break_flag=Trueprint("keep going...")

  

Python (3)-loop statement: Jump out of a multilayer loop from the inner layer

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.