4 Iteration: for-loops

A restaurant bill is made from the various food and drink items ordered. Our program should sum those prices to obtain the expenses, on which the tip will then be added. The algorithm (the ‘recipe’ that is independent of any programming language) that calculates the expenses is as follows.

  1. Let the items be a list of the prices of the food and drinks ordered.
  2. Let the expenses be zero.
  3. For each item in the items list:
    1. Add it to the expenses.
  4. Print the expenses.

Step 3 is a for-loop: it goes through the list to process each item. A for-loop is a form of iteration, the repetition of a block of instructions. Here, step 3.1 is repeated as many times as there are items in the list.

A for-loop can be directly translated to Python. Let me first show the code and then explain it. (If you can’t see all the code, drag the line between the code and the output to the right.)

Text starting with # is a comment. The computer ignores comments, they are just notes by the code’s author to clarify any finer points, like explaining why those particular prices. Such notes come in very handy if the author or someone else needs to change the code later.

I’ve written each step of the algorithm as a comment, immediately followed by its Python translation, to emphasise the correspondence between algorithm and code for pedagogical purposes. I wouldn’t write such comments in my own code.

In line 2 we have a list, which is written as comma-separated values within square brackets [ and ].

The for-loop instruction

for variable in list:
    block

goes through the given list and successively stores each value of the list in the variable and then executes the block, which will usually (but not always, see the exercise below) refer to the variable to get its value.

Here, I add the value of the item to the current expenses and store the result again in expenses, so that it is always up to date. In English: let the new expenses be the old expenses plus the item ordered.

Activity 4.1

For this activity, count and print how many items the list has, instead of adding and printing the items’ values.

First think of the algorithm, which is almost the same as the one above. Hint: the items’ prices are ignored, so the block doesn’t refer to the item variable. If you get stuck, see my algorithm.

Next change the code according to the new algorithm. The output should be 5: that’s how many items are in the list.

You can compare your solution to mine.

Selection Start Functions