Repeating Steps
When the same steps happen again and again, write them once and say how many times to repeat. That is a loop.
- Spot when a plan repeats the same pattern
- Describe a repeat block in plain words
- Explain why loops make plans shorter and easier to fix
Finish first
Topic contents
Lesson 1 of 3
Doing the same thing many times
Imagine walking a square on the floor: forward, turn left, forward, turn left, forward, turn left, forward, turn left. You said the same pair four times. That is boring to write and easy to miscount.
A repeat block is shorthand: 'Repeat 4 times: forward, then turn left.' The computer runs the inside part the right number of times. You write less, and if the turn should be right instead of left, you fix it in one place.
Open the Repeat a square plan in the lab. The list shows the repeat in words, then expands into single steps when the robot runs.
Robot planner
Run the repeat square plan and count how many forwards and turns the robot performs.
Robot planner
Sequences, turns, repeats and choices- Forward
- Forward
- Forward
Start
The robot starts here, facing right. The plan has 3 steps. It will follow them exactly, even when that is wrong.
Lesson 2 of 3
When to use a loop
Use a loop when you can point at a pattern. Clapping games, dance moves, and drawing a fence of identical posts all repeat. If you can say 'do this again until', a loop is probably the right tool.
Be careful with the count. Repeat 4 times is not the same as repeat 5 times. Off-by-one errors happen to experienced coders too: they wanted ten items but the loop ran nine or eleven times.
If the robot stops one side short of a closed square, check whether you repeated three times instead of four.
Lesson 3 of 3
Loops in real programs
Every game that spawns endless enemies uses a loop. Every app that loads a list of messages loops over them. The robot square is the same idea with four turns instead of a thousand enemies.
Later, code will write loops with words like 'for' and 'while'. The robot lab already taught the idea: do this block again until the count runs out.
Try writing 'Repeat 3 times: clap, stomp' and perform it. Then change the count to 5 without rewriting every clap. That is the power of a loop.
Practice
Work these out yourself
No answer key here on purpose: these are the questions worth thinking through before you move on. Open one and work it out.
0/3 attemptedAssessment
Check your understanding
Answer each question, then read the explanation. That is where the learning is.
Finished this topic?
0 of 3 lessons marked done. Marking the topic complete ticks the rest.
