3

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
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40

2 Answers2

8

It only affects the inner loop.

botiapa
  • 353
  • 2
  • 13
3

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.

Abion47
  • 22,211
  • 4
  • 65
  • 88