Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 10 of 25

while loops, break and continue

A while loop repeats as long as its condition stays true. Use it when you do not know in advance how many rounds you need.

count = 1
while count <= 3:
    print(count)
    count += 1

Something inside the loop must change the condition, otherwise the loop never ends. In this app, a program that runs longer than 3 seconds is stopped and explained.

break leaves the loop immediately. continue skips the rest of the current round and moves on to the next.

A classic while pattern takes a number apart digit by digit: n % 10 gives the last digit and n // 10 removes it.

n = 472
while n > 0:
    print(n % 10)
    n = n // 10

Key takeaways

  • A while loop repeats as long as its condition is true, so something inside the loop must change the condition.
  • break leaves the loop immediately. continue skips to the next round.
  • Use while when you do not know in advance how many rounds are needed, and for when you do.
  • n % 10 gives the last digit of a number and n // 10 removes it.

Common mistakes

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.