Introduction to Programming

While Loop

Lesson 8: Loops

What is a While Loop?

A While loop repeats a set of instructions for as long as a condition remains true. As soon as the condition becomes false, the loop stops. In PictoBlox, this is represented by the Repeat Until block — which keeps repeating until the condition becomes true.

In PictoBlox, the 'Repeat Until ()' block works like a While loop. It repeats its contents until the given condition becomes true — meaning it runs while the condition is false.
PictoBlox Repeat Until block from the Control palette with an empty condition slot and space for blocks inside

How the While Loop Works

  • The condition is checked before each repetition.
  • If the condition is false, the blocks inside the loop run.
  • After running, the condition is checked again.
  • This continues until the condition becomes true, at which point the loop stops.

Example: Counting Up to 10

Let's use a Repeat Until loop to count from 1 to 10. We'll use a variable called Counter that starts at 0 and increases by 1 each time the loop runs.

  • Create a variable called Counter.
  • Add a 'When flag clicked' block.
  • Set Counter to 0.
  • Add a 'Repeat Until (Counter = 10)' block.
  • Inside the loop, add 'Change Counter by 1' and 'Say (Counter) for 0.5 seconds'.
  • Click the green flag and watch the sprite count from 1 to 10!
Block coding script showing when flag clicked, set Counter to 0, repeat until Counter equals 10, change Counter by 1 and say Counter for 0.5 seconds
Be careful with While loops! If the condition never becomes true, the loop will run forever and your program will get stuck. This is called an infinite loop.

Subscribe to our newsletter.

Get updates to news and events.