JIT — Intro to Data Science · Python Lab · Problem 13 of 30

Reading out the register

One instruction written once, carried out for every name on the list — however long the list turns out to be.

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.

New word — for loop
for student in students: print(student)
Read it as plain English: for each student in students, print that student.
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.
The loop variable is a name you invent 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 sitsHow often it runs
indented, inside the blockonce for every item
at the margin, after the blockonce, 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

Register: - Anjali - Farhan - Priya - Rohit - Meera End of register

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.

Coming later This loop walks through items that already exist. Counting from 1 to 12 without a list to walk through is what 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.

Your programme

Output

Nothing has run yet.