Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Breaking out of inner loop from nested loop [duplicate]

'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.

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

like image 328
anfwkdrn Avatar asked Jan 23 '26 03:01

anfwkdrn


1 Answers

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)
like image 158
Tom Karzes Avatar answered Jan 24 '26 17:01

Tom Karzes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!