Lesson 6 of 8 · 32 min · Grades 6–8
Loops — repeat without copy-paste
A washing machine does not have a separate button for rinse 1, rinse 2, rinse 3. It repeats the rinse cycle. Copy-pasting print("Rinse") three times works until the manufacturer asks for five rinses — then you have a mess. A for loop is the machine’s timer: same body, counted turns.
Washing machine cycles
Loops repeat a block of work.
You will be able to
- ✓ Use for x in range(n) to repeat work
- ✓ Use the loop variable as a turn counter
- ✓ Keep the repeated lines indented under for
range(n) is n turns, starting at zero
for n in range(3) runs the body three times, with n equal to 0, then 1, then 2. Programmers count from zero because it matches how positions in lists work (next lesson). If you need “rinse 1, 2, 3” for humans, print n + 1 — but understand that n itself is 0-based.
range(5) is five turns, not “up to 5 including 5”. Off-by-one errors (“it ran one extra time”) are normal. Print the loop variable until you trust it.
The body is the cycle
Everything indented under for is the rinse. Un-indent when the repeating should stop. A line that is not indented runs once, after the loop — like “Done” on the machine’s display.
Never copy-paste a block ten times “to be sure”. You will fix a bug in nine copies and miss the tenth. Loops exist so there is one copy of the truth.
What loops are for in real life
Attendance: one print per student. Games: one frame per tick. Science: one measurement per minute. Whenever you hear “for each”, a loop is nearby.
Infinite loops (while True with no way out) freeze a program. In this sandbox, loops are capped so a mistake cannot lock your browser. In real Python you must provide an end.
Words that matter
- Loop
- A block that runs more than once.
- range(n)
- n consecutive integers starting at 0.
- Loop variable
- The name (n, i, step) that changes each turn.
Common mistakes
Avoid: range(3) thought to mean 1, 2, 3.
Do this: It means 0, 1, 2 — three turns.
Avoid: Forgetting to indent the body.
Do this: The repeated work must sit under the for line.
Example program — Three rinse cycles
The number after Rinse comes from the loop variable. Try range(5).
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Your turn — Assembly countdown
Loop 4 times and print the word Clap at least once (you may print it every turn).
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Self-assessment
Check your understanding before you mark the lesson complete.
Progress is stored in a browser cookie on this device.