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