1

Is there any opportunity or workaround in Python so you can break or continue the outer loop? For example:

for i in range(1, 5):
    for j in listD:
        if smth:
            continue <-- I want this to work for outer loop

Thanks.

Newcommer2
  • 19
  • 1

2 Answers2

1

The behavior that you expect is not fully clear, but you could use a flag:

break_flag = False
for i in range(1, 5):
    if break_flag:
        break_flag = False
        continue
    for j in listD:
        if smth:
            break_flag = True
            break

or a try/except block:

for i in range(1, 5):
    try:
        for j in listD:
            if smth:
                raise StopIteration # you might want to use a custom error
    except StopIteration:
        continue
mozway
  • 194,879
  • 13
  • 39
  • 75
-2

Just indent the code correctly. Python uses spaces to know which statements are in scope. If you use 4 spaces to indent code, then another 4 spaces means an inner code block (8 spaces in total). This is like nesting in a programming language like C or Java but without the "{ }". To end code block and get to outer loop just write with 4 spaces less in the next line of code.

One important thing to note is number of spaces used should be consistent. You must use consistent units of spaces. If one indent block is 4 spaces, you must use multiples of 4 to intent code in the same file. Ideally use 4 spaces as a unit of indent for statements sin same code block.

for i in range(1, 5):
    #outer loop statements here
    for j in listD:
        #inner loop statements here
        pass
    #outer loop statements again
    if smth:
        #this if block statements is part of outer loop statements
        continue 

Now continue statement gets executed after inner loop is executed. You need continue statement only if you have statements which you need to skip over.

codefire
  • 393
  • 1
  • 3
  • 13
  • I think OP wants to break/continue both loops from within the inside loop – mozway Oct 01 '21 at 08:58
  • You're ignoring the if statement in the inner loop. – khelwood Oct 01 '21 at 09:00
  • I think OP knows how to break continue, but doesn't know how to put the continue block in the outer loop. OP says "<-- I want this to work for outer loop" – codefire Oct 01 '21 at 09:00
  • I think `continue` must be made dependent on the condition (I imagine there might be some code after the inner loop) – mozway Oct 01 '21 at 09:03
  • I get that. But its pointed in the question that OP wants continue statement in outer loop. This is a typical mistake new comers in python come across. – codefire Oct 01 '21 at 09:04