Grade 7 Computer Science · Loops
A loop — repeating without duplicating
Three parts: the body that repeats, the check that decides, and the progress that nears the end.
Five identical lines, and a fix in four
You can print five names with five nearly identical lines, and it even works — until the day something in all of them needs fixing and you fix only four. There is a way to write the line once, but it needs three parts, and whoever forgets one of them gets a program that never finishes.
Until here every line was written once and ran once. But much of what programs do is the same thing over and over on different data: printing every name in a list, computing a mark for every student, checking every character in a word. The line could have been duplicated a hundred times — and a loop exists precisely so that you need not.
count = 1
while count <= 3:
print(count)
count = count + 1| The part | What it does |
|---|---|
| The body | What repeats |
| The check | Decides whether to repeat |
| The progress | Changes something the check looks at |
Why duplication is worse than a loop
Suppose you duplicated a line five times and then found something in it needed fixing. Now you have five places to fix, and it takes forgetting only one for the program to behave correctly in most cases and incorrectly in one — exactly the hardest kind of bug to locate. In a loop there is one place. A second advantage, no less important: the number of repetitions need not be written in the code. It can come from a list’s length or from a condition, so the same program works on ten items and on ten thousand without a line changing.
Example 1 — following a loop
- The counter starts at one, and the check is true.
- The body prints, and the progress raises it to two.
- So too at three, and then the counter is four.
- The check is no longer true, and the loop stops.
Example 2 — why duplication breaks in maintenance
- The same line appears five times.
- It is fixed in four places out of five.
- The program is correct in most cases only.
- And the bug looks random, and is very hard to locate.