Leave a loop early with break, or skip the rest of one pass with continue.
Each loop panel shows the values the loop walks over; the highlighted cell is the current one.
0printed2skipped by continue5break6never reached
break statement
# break exits the loop
for i in range(10):
if i == 5:
break
print(i)
# ans: 0, 1, 2, 3, 4
continue statement
# continue skips current iteration
for i in range(5):
if i == 2:
continue
print(i)
# ans: 0, 1, 3, 4
# break in while loop
count = 0
while True:
count += 1
if count == 3:
break
# ans: count is 3
while True never ends on its own: break is the only way out.
# continue in while
x = 0
while x < 5:
x += 1
if x == 3:
continue
print(x)
# ans: 1, 2, 4, 5 (skips 3)
The x += 1 comes before the continue; put it after and the loop would never end.
# break only exits inner loop
for i in range(3):
for j in range(3):
if j == 1:
break
print(f"i={i}, j={j}")
# ans: i=0,j=0 then i=1,j=0 then i=2,j=0
Write down the output, then press → to run the loop.
# what prints?
for i in range(5):
if i == 3:
break
print(i)
# ans: 0, 1, 2
# continue effect?
for i in range(5):
if i % 2 == 0:
continue
print(i)
# ans: 1, 3 (skips even numbers)
# multiple breaks?
for i in range(10):
if i == 3:
break
if i == 5:
break
print(i)
# ans: 0, 1, 2 (first break stops it)
# what is i?
for i in range(10):
if i == 5:
break
# ans: i is 5
# nested break?
for i in range(3):
for j in range(3):
if i == j == 1:
break
print(i, j)
# ans: (0,0) (0,1) (0,2) (1,0) (2,0) (2,1) (2,2)
# what happens?
for i in range(5):
continue
print(i)
# ans: nothing (continue skips print)
# tricky continue?
for i in range(3):
if i == 1:
i = 10
continue
print(i)
# ans: 0, 2 (i=10 doesn't affect next iteration)
# what prints?
for i in range(5):
if i < 2:
continue
if i > 3:
break
print(i)
# ans: 2, 3
# break immediately?
for i in range(5):
break
print(i)
# ans: nothing (breaks before print)
# continue then break?
for i in range(10):
if i % 2 == 0:
continue
if i == 5:
break
print(i)
# ans: 1, 3
breakLeaves the loop at once; the remaining items are never reached.
continueSkips the rest of this pass and goes straight to the next item.
In nested loops, both affect only the loop they are directly inside.
After a break, it keeps the value it had; changing it inside a for does not change the next item.