Adding up the cost
Let us consider a shopping list. All of the prices of the items are stored in an array as shown below
prices = [3.99, 12.99, 4.49, 18.99, 0.99, 0.89, 2.35]
To add up the total for this we need to loop over each price. With each price we need to add it to a total (which is initially zero) and then finally print the result out. These would be the basic steps and translating them into code we get –
prices = [3.99, 12.99, 4.49, 18.99, 0.89, 2.35]
x = 0
total = 0
while x < len(prices):
total = total + prices[x]
x = x + 1
print "total cost is", total
Looping over an array in this way is a easy way to do calculations on the contents of the array. In this case to work out the sum of all prices.
Add a 0.99 item to the end of the array and run to move onto the next exercise.
Output: (clear)











