Skip to content
CodeNest

Control FlowLesson 8 of 1913 min

while Loops, break, and continue

Repeat for as long as a condition holds — and stay out of infinite loops.

By the end you will be able to

  • Write a while loop with a condition that eventually becomes False
  • Exit early with break and skip an iteration with continue
  • Recognise and avoid infinite loops

Use for when you know what to loop over. Use while when you only know when to stop.

A while loop rechecks its condition before every pass and keeps going while it is truthy.

Python
Output
3
2
1
Liftoff!
— expected output; press Run to execute it yourself

break and continue

  • break leaves the loop immediately
  • continue skips the rest of this pass and jumps to the next one

Both work in for loops too.

Python
Output
First multiple of 3: 9
1 3 5 7 9 
— expected output; press Run to execute it yourself

A processing queue

while shines when the collection shrinks or grows as you work through it.

Python
Output
Running render... 3 left
Running compress... 2 left
Running upload... 1 left
Running notify... 0 left
Queue empty.
— expected output; press Run to execute it yourself

Exercise

Write a function digit_count(n) that returns how many digits a positive integer has, using a while loop and //. digit_count(4071) should return 4.

Python
Output

Press Run to execute this code.

Check your understanding

0/2 answered
  1. 1.What does break do inside a loop?
  2. 2.Which loop is the natural choice when you do not know in advance how many iterations you need?