A loop is a block that repeats commands. Instead of writing the same block over and over, you put it inside a loop and tell the loop how many times to run.
The same code, two ways
Imagine you want a sprite to jump 3 times. Without a loop you write ‘jump’ three times. With a loop you write ‘jump’ once, inside a repeat 3 times block.
| Without a loop | With a loop |
|---|---|
| jump jump jump | repeat 3 times { jump } |
Both make the sprite jump 3 times. The loop is shorter and easier to read.
Drawing a square with a loop
A square has 4 equal sides and 4 turns. To draw one, the sprite moves forward, then turns, and does this 4 times.
Put these steps in order to draw a square:
- Start the "repeat 4 times" loop
- Move forward 100 steps
- Turn right 90 degrees
- Loop back to the start, 4 times in all
Counting how many times a loop runs
The number in the loop tells you how many times the blocks inside run. So if there are 2 blocks inside a repeat 4 times loop, the sprite does 8 actions in total (2 blocks × 4 turns).
The square above needs just one small loop to draw.