Quarry School

Read a for loop — quick review

In plain words

A ticket checker at a gate takes the tickets of the people in line one at a time, from the front, and does the same check on each.

Rule

A for loop over a sequence runs its indented body once for each item, in order, unless a break ends it sooner. Before each pass, the name after for is given the next item. When the items run out, the program carries on with the first line after the body. An empty sequence gives no passes.

Step

  1. Find the sequence after in and write its items in order. A string gives one item for each character.

  2. Find the body: the lines indented under the for line.

  3. For each item, write the loop name's value, then run the body's lines in order with that value.

  4. After the last pass, move to the first line after the body. In this unit's programs that is the next line indented no further than the for line.

  5. Count the passes: one for each item, unless a break ends the loop sooner. Check that the output holds what the body displays once for each pass.

Trap

A line meant to run once can slip into the body. If print("done") were indented under the for line, it would run on every pass and the output would hold done three times. Check the indentation of each line below a for line.

The loop name keeps its last value after the loop ends. After the loop over "MAP", letter still holds P. Use the loop name inside the body, where it holds the current item.