Tutorpip← About this lessonOpen the sheet →Download PDF
Ages 8+ · Coding · Loops
Forever loops and how to stop
1forever2 dance3 has the music stopped?4 no: go round again5 yes: leave the loop
A forever loop with a way out.
The big ideaA forever loop never ends by itself. Give it a way out, like a check.

How it works

A forever loop never ends by itself.

Sometimes that is just right, like a ticking clock or a game that waits for your tap.

But a forever loop needs a way out, or the program gets stuck.

A check inside the loop is a way out: no means go round again, and yes means leave the loop.

Counting loop• repeat 5 times: hop• stops by itself• after 5 hopsForever loop• forever: dance• never stops by itself• needs a way out
Two kinds of loop.

Example 1: Bo does not stop

  1. Mina writes one loop: forever dance.
  2. The music ends, but nothing in the loop checks the music.
  3. Bo keeps dancing, even down the hall at lunch.

Example 2: The off switch

  1. Mina flicks the off switch on Bo's back, and Bo goes quiet.
  2. An off switch stops any loop.
  3. But there is a neater way.

Example 3: Add a check

  1. Mina adds a check inside the loop: has the music stopped?
  2. If the answer is no, Bo goes round again. If the answer is yes, Bo leaves the loop.
  3. Bo can loop forever and still stop.
1forever2 dance3 has the music stopped?4 no: go round again5 yes: leave the loop
Lines 3 to 5 are the way out.

Example 4: Which gadgets are forever loops?

  1. A fan spins until someone switches it off, and a wall clock keeps ticking on and on.
  2. An egg timer rings and stops by itself, and a hopping toy that hops 5 times and sleeps stops by itself.
  3. The fan and the clock are like forever loops. The timer and the toy are like counting loops.

Words to know

forever loop
A loop that never ends by itself.
way out
A check, a stop button or a switch that ends a loop.
check
A yes or no question asked inside a loop.

Watch out

Try it

  1. The check says yes. Does Bo go round again or leave the loop?
  2. Does a forever loop stop by itself?
  3. A toy hops 5 times and sleeps. Is it a forever loop or a counting loop?
  4. Name one way out of a loop.
  5. True or false: playing the song louder stops Bo's loop.
Answers: 1. Leaves the loop · 2. No · 3. A counting loop · 4. A check, a stop button or the off switch · 5. False
Try at homeLook for things that keep going until someone stops them, like a fan, a clock or a fridge light. Find two that go until switched off and one that stops by itself, like an oven timer, then talk about how each one is told to stop.
For grown-upsDo the Mission: look around the house for things that keep going until someone stops them, like a fan, a clock or a fridge light, and find one that stops by itself, like an oven timer. Talk about how each one is told to stop.
Open these notes on screenScan the code, or go to tutorpip.com.