I am learning about nested loops and I have come across the use of break. I don't quite understand where to place break in the nested loop to get the correct output. I have tried three different codes, and don't understand them fully.
code 1: Interruption of the loop after the first round of j (j=0), but continuation of the nested loop itself - this code is understandable for me and is used as comparison for the next codes.
for i in range(6):
print('hello')
if i<=3:
for j in range(3):
print('hi')
break
print('bye')
code 2: interrupts the entire nested loop after the first round (i=0, j=0,1,2), why doesn't it just interrupt j? Compared to code 1, I thought break has moved from the single round of loop j to the whole loop of j. But this does not seem to be the case. And I have read, break interruppts the closest loop, which would be j.
for i in range(6):
print('hello')
if i<=3:
for j in range(3):
print('hi')
break
print('bye')
code 3: And here I moved break even further, but get the same result as code 2.
for i in range(6):
print('hello')
if i<=3:
for j in range(3):
print('hi')
break
print('bye')
break
breaks out of the innermost loop the break
statement is directly inside of.
for i in range(...):
...
break
This break
is inside the for i
loop, so it'll stop the entire for i
loop. Any loops that are outside are untouched:
for j in ...:
for i in ...:
break # Terminate the `for i` loop
# The `for j` loop continues
Placing break
next to another loop affects the loop break
is inside of anyway:
for i in ...:
for j in ...:
print('Hello')
break
# Outside `for j`, but inside `for i`,
# so only `for i` loop can be affected by this `break`
"break
interrupts the closest loop" means "break
interrupts the innermost loop".
Placing break
inside an if
statement still terminates the loop the break
is inside of, but only if
some condition is met:
for i in ...:
for j in ...:
if i > j: break # Get out of the `for j` loop ONLY IF `i > j`