Skip to content

while Loops, break and continue

You will repeat code while a condition is true and control a loop with break and continue.

10 min read 10 quiz questions

Counter loops

while condition:
    do_work()
A counter loop repeats while its counter meets the condition.
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

continue skips the rest of the current loop repeat.
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

break exits a loop early; pass is a placeholder that does nothing.
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.

Example
fund = 0
week = 0
while True:
    week += 1
    fund += 300
    if fund >= 1000:
        break
print(week, "weeks")

How it works, step by step

  1. while True loops forever unless something breaks out.
  2. Each week adds 300 taka.
  3. After week 4 the fund is 1200, the condition trips, and break exits.

References & Further Reading

Related entries from PyLabs's own reference library.

  • iter() (Return an iterator for a collection or other iterable.)
  • next() (Get the next item from an iterator.)
  • bool() (Convert a value to True or False.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Set 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
Want another challenge on this module? More coding practice

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 completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet