Reputation: 131
When using nested for loops, if I use continue inside the inner nested for loop, does the scope of that continue only apply to the inner loop or will it continue the outer loop?
Note: For what I am working on I only want the continue to affect the nested loop
b = ["hello"] * 5
d = ["world"] * 10
for a in b: # Outer Loop
x = 1 + 1
for c in d: # Nested Loop
if c:
x += 1
else:
continue # Does this affect the Nested Loop or the Outer Loop
Upvotes: 4
Views: 3210
Reputation: 11
As @botiapa said : It only affects the inner loop.
Now, if you want to make a working process to affect upper scope loop you have 2 solutions:
1 - Use variables at the top of the upper scope loop:
b = ["hello"] * 5
d = ["world"] * 10
for a in b: # Outer Loop
outer_loop_should_break = False
x = 1 + 1
for c in d: # Nested Loop
if c:
x += 1
else:
outer_loop_should_break = True
break # Does this affect the Nested Loop
if outer_loop_should_break:
break
else:
# do something
2 - Use Exceptions to have better traces:
class ShouldBreak(Exception):
pass
class ShouldContinue(Exception):
pass
b = ["hello"] * 5
d = ["world"] * 10
for a in b: # Outer Loop
x = 1 + 1
try:
for c in d: # Nested Loop
if c:
x += 1
else:
raise ShouldBreak("explain why")
# Or
raise ShouldContinue("explain why")
except ShouldBreak as sb:
print(str(sb))
break
except ShouldContinue as sc:
print(str(sc))
continue
# do something else after
If you really want to use namespaces for loop, you can switch to JavaScript and use label on loops : Docs here
Upvotes: 0
Reputation: 24736
Loop control keywords like break
and continue
only affect the closest loop in scope to them. So if you have a loop nested in another loop, the keyword targets whatever loop it is immediately within, not loops farther up the line.
Upvotes: 3