Decisions and loops
While loops, break, and continue
Repeat while a condition holds, stop early with break, and skip one iteration with continue.
Lesson 16 of 63
Reading: about 2 min
Lesson + practice: about 14 min
Difficulty: Beginner
On this page4 sections
A while loop repeats while its condition is True. Update the value used by the condition so the loop can end. Otherwise it may run indefinitely.
count = 1
while count <= 3:
print(count)
count += 11 2 3
Stop or skip
break exits the nearest loop. continue skips the rest of the current iteration and moves to the next one. In a while loop, update the counter before continue so the loop can still finish.
for number in range(1, 7):
if number == 2:
continue
if number == 5:
break
print(number)1 3 4
Why this works
A while loop checks its condition before each iteration. If the condition starts False, its body runs zero times. break stops the nearest loop immediately; continue skips to the next condition check. For counter-based while loops, update the counter before any possible continue to avoid repeating the same value forever.
Practice
Use a while loop to print 1 through 5. Skip printing 3 with continue, and ensure the counter still advances on every iteration.
Why must the while-loop counter change?
Reveal answer
Without a change that makes the condition False, the loop can continue indefinitely.
Try another case
If count starts at 4, how many times does while count <= 3 run?
Check your answer
Reveal answer
Zero times. The condition is False at the first check.
Your progress
Reveal the check answer or reach the end to complete this lesson.