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.
- Let items be a list of the prices of the food and drinks ordered.
- Let the expenses be zero.
- For each item in the items list:
- add it to the expenses.
- 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.
: 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'.