3

'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

anfwkdrn
  • 327
  • 1
  • 7

3 Answers3

1

Set additional flag that skips exec on fail:

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

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

# 2
    for a in range(3):
        print(a)
How about nope
  • 752
  • 4
  • 13
1

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)
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

This is my take on it:

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

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

    # 2
    if not error:
        for a in range(3):
            print(a)

Result:

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
Cow
  • 2,543
  • 4
  • 13
  • 25