Break and Continue Statement in Nested Loops
So I Was Experimenting the for-Loop in Python and I Decided Let Me Use Continue and Break Statements for Experimentation and I Got to Know What's the...
So i was experimenting the for-loop in Python and i decided let me use continue and break statements for experimentation and i got to know what's the difference. So "break" exits your loop completely and "continue" skips the current iteration of the loop and continues it but the headache started when i experimented with the "break" and "continue" in nested loops and i see no difference in the code which i have pasted below
1.)"break" nested loop.
for i in range(6):
print("iteration {}".format(i))
for j in range(6):
if i == 3:
break
print(j)
2.) "continue" nested loop
for i in range(6):
print("iteration {}".format(i))
for j in range(6):
if i == 3:
continue
print(j)
And my question is why does "continue" and "break" act the same in nested-loops in my code???
for those who are wondering Outputs for the loops
1.)for "break"
iteration 0
0
1
2
3
4
5
iteration 1
0
1
2
3
4
5
iteration 2
0
1
2
3
4
5
iteration 3
iteration 4
0
1
2
3
4
5
iteration 5
0
1
2
3
4
5
2.)Output for "continue"
iteration 0
0
1
2
3
4
5
iteration 1
0
1
2
3
4
5
iteration 2
0
1
2
3
4
5
iteration 3
iteration 4
0
1
2
3
4
5
iteration 5
0
1
2
3
4
5
Would be great help for the answer!!...thanksss..
1 Answer
The break version:
When i == 3 the break breaks out of the j-loop at the first iteration so it does nothing.
The continue version:
When i == 3 the continue goes back to the top of the j-loop before the print() call on every iteration so the print() call doesn't happen.