How to break out of multiple loops?

后端 未结 30 3384
情书的邮戳
情书的邮戳 2020-11-21 05:48

Given the following code (that doesn\'t work):

while True:
    #snip: print out current state
    while True:
        ok = get_input(\"Is this ok? (y/n)\")
          


        
30条回答
  •  Happy的楠姐
    2020-11-21 06:18

    By using a function:

    def myloop():
        for i in range(1,6,1):  # 1st loop
            print('i:',i)
            for j in range(1,11,2):  # 2nd loop
                print('   i, j:' ,i, j)
                for k in range(1,21,4):  # 3rd loop
                    print('      i,j,k:', i,j,k)
                    if i%3==0 and j%3==0 and k%3==0:
                        return  # getting out of all loops
    
    myloop()
    

    Try running the above codes by commenting out the return as well.

    Without using any function:

    done = False
    for i in range(1,6,1):  # 1st loop
        print('i:', i)
        for j in range(1,11,2):  # 2nd loop
            print('   i, j:' ,i, j)
            for k in range(1,21,4):  # 3rd loop
                print('      i,j,k:', i,j,k)
                if i%3==0 and j%3==0 and k%3==0:
                    done = True
                    break  # breaking from 3rd loop
            if done: break # breaking from 2nd loop
        if done: break     # breaking from 1st loop
    

    Now, run the above codes as is first and then try running by commenting out each line containing break one at a time from the bottom.

提交回复
热议问题