Loops 🔁
What You'll Learn
- What a loop is and why programmers use them
- How the Repeat control runs your program multiple times
- How loops make complex drawings from simple programs
Don't Repeat Yourself
In Lesson 4 you needed 8 blocks to draw a square — the same 2 blocks repeated 4 times. Imagine if you needed to draw the same square 20 times. That would be 160 blocks!
Programmers have a rule: Don't Repeat Yourself (often shortened to DRY). If you are writing the same thing over and over, there is almost always a smarter way.
That smarter way is called a loop.
A loop is a section of code that runs automatically a certain number of times. Instead of writing 8 blocks for a square, you write 2 blocks and tell the program to repeat them 4 times. Same result, less work.
The Repeat Control
In the coding widget below, look at the left panel. At the bottom you will see a Repeat ___ times input. This is your loop control.
When you click Run, your entire program runs once for each repeat. Set it to 4 and click Run — your program runs 4 times back to back.
Here is the key insight: the square program from Lesson 4 is just 2 blocks repeated 4 times!
- Build just: Move Forward 80 → Turn Right 90°
- Set Repeat to 4
- Click Run — it draws a complete square!
Video games use loops constantly. Every frame of a game — your character moving, enemies thinking, the score updating — happens inside a giant loop running 60 times per second. Without loops, games could not exist!
Spirals and Surprises
Loops open up shapes that would take hundreds of blocks to build by hand. Try this:
- Program: Move Forward 5 → Turn Right 90°
- Set Repeat to 40
What do you think it will draw? Run it and see! Now try changing the step size or repeat count and see how the shape changes.
Step 1: Draw a square using only 2 blocks and the Repeat set to 4.
Step 2: Now change Repeat to 8 with the same 2 blocks. What shape do you get?
Step 3: Try: Move Forward 10 → Turn Right 90° with Repeat set to 20. What happens?
Record your observations! Changing one number can completely change the drawing.
1. What is the main benefit of using a loop?
2. You build: Move Forward 80 → Turn Right 90° with Repeat set to 4. What does it draw?
3. What does the programmer rule DRY stand for?