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.

Free course

Simple coding

4 Iteration (part 1)

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.

Activity 8

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)] .

SCOD_1

Take your learning further

Making the decision to study can be a big step, which is why you'll want a trusted University. The Open University has 50 years’ experience delivering flexible learning and 170,000 students are studying with us right now. Take a look at all Open University courses.

If you are new to university level study, find out more about the types of qualifications we offer, including our entry level Access courses and Certificates.

Not ready for University study then browse over 900 free courses on OpenLearn and sign up to our newsletter to hear about new free courses as they are released.

Every year, thousands of students decide to study with The Open University. With over 120 qualifications, we’ve got the right course for you.

Request an Open University prospectus