Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Breaking out of inner loop from nested loop

‘break’ is used to break out of the nested loop.

main_keyword = ["11111", "22222", "333333", "44444", "55555"]

for pro in main_keyword:
    # 1
    for i in range(3):
        if pro == '333333':
            print(pro, "failure")
            break
        else:
            print(pro, "Pass")
            pass

    # 2
    for a in range(3):
        print(a)

However, the #1 for loop escapes, but the #2 for loop is executed.

11111 Pass
11111 Pass
11111 Pass
0
1
2
22222 Pass
22222 Pass
22222 Pass
0
1
2
333333 failure
0
1
2
44444 Pass
44444 Pass
44444 Pass
0
1
2
55555 Pass
55555 Pass
55555 Pass
0
1
2

What I want is if pro == ‘333333’ , then proceed to the next operation of the top-level loop without working on both for loop #1 and #2.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

11111 Pass
11111 Pass
11111 Pass
0
1
2
22222 Pass
22222 Pass
22222 Pass
0
1
2
333333 failure
44444 Pass
44444 Pass
44444 Pass
0
1
2
55555 Pass
55555 Pass
55555 Pass
0
1
2

I want the above result. help

>Solution :

It looks like you want a multi-level continue. But Python doesn’t support multi-level break or continue. However, you can achieve the equivalent effect by using a flag:

main_keyword = ["11111", "22222", "333333", "44444", "55555"]

for pro in main_keyword:
    # 1
    fail = False
    for i in range(3):
        if pro == '333333':
            print(pro, "failure")
            fail = True
            break
        else:
            print(pro, "Pass")
            pass

    if fail:
        continue

    # 2
    for a in range(3):
        print(a)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading