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.

The body is written once; the check decides how many times it runs.
count = 1
while count <= 3:
    print(count)
    count = count + 1
The partWhat it does
The bodyWhat repeats
The checkDecides whether to repeat
The progressChanges 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

  1. The counter starts at one, and the check is true.
  2. The body prints, and the progress raises it to two.
  3. So too at three, and then the counter is four.
  4. The check is no longer true, and the loop stops.

Example 2 — why duplication breaks in maintenance

  1. The same line appears five times.
  2. It is fixed in four places out of five.
  3. The program is correct in most cases only.
  4. And the bug looks random, and is very hard to locate.
Without line 4, count would stay 1 and the check would be true forever.