Skip to content
Science, Maths & Technology
  • Activity
  • 10 mins
  • Level 1: Introductory

Simple Coding - Iteration

Updated Thursday 10th September 2015

Learn about repetition in 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.

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.

Exercise: 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.

Next you'll learn how to simplify the above code - 'Simple Coding - Functions'.


For further information, take a look at our frequently asked questions which may give you the support you need.

Have a question?