while Loops, break and continue
You will repeat code while a condition is true and control a loop with break and continue.
Counter loops
while condition:
do_work()
count = 1
while count <= 3:
print(count)
count += 1
The condition is checked before each repeat. After printing a count, count += 1 moves it closer to 4. When the count is 4, the condition is false and the loop stops.
Infinite loops and continue
number = 1
total = 0
while number <= 5:
if number == 3:
number += 1
continue
total += number
number += 1
print(total)
The loop adds 1, 2, 4, and 5. When the number is 3, it is increased first and continue skips the addition, so the final total is 12.
Break else and pass
number = 1
while number <= 5:
if number == 4:
break
print(number)
number += 1
else:
print('Finished normally')
if number == 4:
pass
break stops the loop as soon as the number reaches 4, so the loop's else block does not run. pass lets you write an empty block while you plan its code; it produces no output.
Key points
- A while loop repeats while its condition stays true.
- Update a counter or another value to avoid an infinite loop.
- Use += to accumulate a running total.
- break exits the nearest loop immediately; continue skips one repeat.
- while else runs only when the loop ends without break.
Worked example
Save pocket money weekly until the fund reaches 1000 taka, then stop — break ends the loop early.
fund = 0
week = 0
while True:
week += 1
fund += 300
if fund >= 1000:
break
print(week, "weeks")
How it works, step by step
- while True loops forever unless something breaks out.
- Each week adds 300 taka.
- After week 4 the fund is 1200, the condition trips, and break exits.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetSet number to 1 and total to 0. Use a while loop to add the numbers 1 through 4 to total, then print it.
Expected output:
10
# Write your code below
Check yourself
while Loops, break and continue quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.