LEARN · PRACTISE · DISCOVER
Loops: Repeat and Forever
Imagine you want a sprite to walk 10 times. You could drag 10 move blocks into a long stack. But coders have a smarter tool: the loop. A loop repeats blocks over and over. In this lesson you will learn the two most useful loops in Scratch: repeat and forever.
The repeat loop
The repeat (10) block is in the orange Control category. It is shaped like a letter C. Blocks you put inside it repeat the number of times you choose.
when green flag clicked
repeat (10)
move (10) steps
wait (0.1) seconds
endThis moves the sprite 10 steps, 10 times, for 100 steps in total. The small wait makes the movement smooth enough to watch.
Drawing a square
To draw a square, you move and turn four times. With a loop, it is only a few blocks. (Add the green Pen extension using the button at the bottom left to draw.)
when green flag clicked
pen down
repeat (4)
move (100) steps
turn right (90) degrees
endThe forever loop
The forever block repeats its blocks forever, until you click the stop sign. Use it for things that should keep happening all through a game, like background music or an enemy that never stops moving.
Example: a walking cat
Mia wanted the Scratch Cat to walk back and forth across the stage. She used a forever loop with costumes:
when green flag clicked
forever
move (10) steps
next costume
if on edge, bounce
wait (0.1) seconds
endnext costume switches between the cat’s two costumes, so its legs look like they are walking. if on edge, bounce turns it around at the edges.
Repeat or forever?
| Use | When | Example |
|---|---|---|
repeat | you know how many times | jump 3 times, draw a square |
forever | it should never stop | moving clouds, music, game checks |
Loops save time and reduce mistakes
Loops make your code shorter and easier to change. If you want the cat to walk faster, you only change one number inside the loop, not ten separate blocks.
Common bug: the loop is too fast
Computers are very fast. Without a wait block inside a loop, an animation may finish before you can see it, or a sprite may zoom off the stage in a flash. If something happens too quickly, add wait (0.1) seconds inside the loop.
Nested loops
You can put a loop inside another loop. For example, put the square-drawing loop inside repeat (6) and add turn right (60) degrees after it. You will draw six squares in a beautiful flower pattern!
Key takeaways
- A loop repeats the blocks inside it.
repeat (n)repeats a set number of times.foreverrepeats until the project is stopped.- Use
next costumeinside a loop to animate a sprite.
Practice
Make a sprite spin all the way around in a circle using a repeat loop. Hint: a full circle is 360 degrees.
Answer: one solution is when green flag clicked, then repeat (24) with turn right (15) degrees and wait (0.05) seconds inside. 24 × 15 = 360 degrees, a full circle.