Doing the same thing to every item
Problem 6 reached into a list by position: students[0], students[1], and so on. That works while you know there are five students. Write it out five times and the sixth student is silently ignored; write it out six times and a five-student list stops the programme.
A loop says the thing you actually mean: do this once for every item, however many there are.
Python takes the first item out of the list, puts it in a box called
student, and runs the indented block. Then it does the same with the second item. Then the third. When the list runs out, it stops and carries on with whatever comes after the block.student is not a keyword and Python attaches no meaning to it. You could write for x in students: and it would work identically. Choose a name that says what one item is, and keep the plural for the list — for student in students reads correctly, and the near-identical pair is exactly why the two get mixed up.Inside the block,
student is one name. students is still the whole list.The indentation decides how many times a line runs
| Where the line sits | How often it runs |
|---|---|
| indented, inside the block | once for every item |
| at the margin, after the block | once, when the loop has finished |
This is the same rule as problems 10 and 12, with a sharper consequence. A closing line pushed in by four spaces is not merely attached to the wrong branch — it is printed five times, or two hundred times, once for every row in your data.
What you are building
Seven lines of output from six lines of programme — and the same six lines would handle a register of two hundred without a word being changed.
range() does, in problem 14, and keeping a running total as you go is problem 15.Build the programme
Your plan
The steps still to place
The whole programme is laid out below. Five pieces are missing. Two of them are the difference between one name and the whole list, and two are blank space that decides how many times a line runs.
Leave nothing on "choose…". A wrong pick does not always cause an error — sometimes it just prints something you did not expect, which is the harder kind of mistake to spot.
Run and read
Here is the whole programme. The register is yours to change — make it longer, make it shorter. Notice that nothing in the loop needs to know how many names there are.