Skip to content
Skip to main content

About this free course

Author

Download this course

Share this free course

Simple coding
Simple coding

Start this free course now. Just create an account and sign in. Enrol and complete the course for a free statement of participation or digital badge if available.

4 Iteration (part 1)

In this section you will learn about repetition in the Python programming language. 

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 (which is independent of any programming language) is as follows.

  1. Let 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:
    • add it to the expenses.
  4. print the expenses

Step 3 is called an iteration: it goes through the list to process each item. This can be directly translated to Python.

Interactive feature not available in single page view (see it in standard view).

In Python, any line starting with # is a comment. The computer ignores comments, they are just notes by the code’s author to clarify any finer points. Such notes come in very handy if the author (or someone else) needs to change the code later.

In Python, lists are simply comma-separated values, within square brackets.

The ‘for variable in list: block’ instruction 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. In this case, 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 7

Calculate and print how many items were ordered, i.e. 5 in the example above. First change the algorithm, then translate it to code. Hint: you need to count the items in the list, their prices are irrelevant. If you get stuck, you can see the algorithm  [Tip: hold Ctrl and click a link to open it in a new tab. (Hide tip)] .