LightMySky

Condition-Controlled Loops

Repeating for as long as a condition stays true, for when the number of repeats is not known in advance, and making sure something inside the loop can make the condition false.

No account needed. Progress saves in this browser.

What a learner can do afterwards

  • Write a loop that keeps asking until the input is valid
  • Point at the line that lets the loop end, and say what happens without it
  • Choose between a counted loop and a condition-controlled loop for a described task

1 · Read

A while loop is a condition-controlled loop. It keeps repeating its block for as long as its condition stays True, and stops the moment it turns False. A for loop is different: it repeats a set number of times, or once for each item in a list. Pick while when you do not know ahead of time how many repeats you need.

The computer checks the condition, runs the body once if it is True, then checks again. If it is False, the loop ends and the program moves on. Any True or False expression works as the condition, including compound ones built with and and or. Because the check repeats every pass, something inside the body must be able to change it.

Try it together

To keep asking until the right password is typed, set keep_asking to True and loop while it holds. Inside, ask for an entry, and set keep_asking to False when the entry matches. The ask line is what lets the loop end. Without it the condition could never flip, and the loop would run forever.

Good to know

Choose by counting what you know. A class list of known size calls for a for loop. Waiting for a signal, a password or a sensor reading calls for while. Before you run it, point at the line inside that can flip the condition and ask what happens without it.

While repeats until its condition flips, so the body must hold the line that flips it.

2 · Watch

Take it off screen

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.

Spotted a problem on this page? Tell us
Condition-Controlled Loops · Computing, ages 15 to 16 · LightMySky