Ad

How To Add A Running Total Together?

- 1 answer

I have a homework task to basically create a supermarket checkout program. It has to ask the user how many items they are, they then put in the name and cost of the item. This bit I've worked out fine, however I'm having trouble adding the total together.

The final line of code doesn't add the prices together, it just lists them.

Code so far

print "Welcome to the checkout! How many items will you be purchasing?"
number = int (input ())

grocerylist = []
costs = []

for i in range(number):
    groceryitem = raw_input ("Please enter the name of product %s:" % (i+1))
    grocerylist.append(groceryitem)
    itemcost = raw_input ("How much does %s cost?" % groceryitem)
    costs.append(itemcost)

print ("The total cost of your items is " + str(costs))

This is for a homework task for an SKE I'm doing however I'm stumped for some reason!

The expected output is that at the end of the program, it will display a total costs of items added into the program with a £ sign.

Ad

Answer

You have to loop through list to sum the total:

...
total = 0
for i in costs:
    total += int(i)
print ("The total cost of your items is " + str(total)) # remove brackets if it is python 2

Alternative (For python 3):

print("Welcome to the checkout! How many items will you be purchasing?")
number = int (input ())

grocerylist = []
costs = 0   # <<

for i in range(number):
    groceryitem = input ("Please enter the name of product %s:" % (i+1))
    grocerylist.append(groceryitem)
    itemcost = input ("How much does %s cost?" % groceryitem)
    costs += int(itemcost)   # <<
print ("The total cost of your items is " + str(costs))

Output:

Welcome to the checkout! How many items will you be purchasing?
2
Please enter the name of product 1:Item1
How much does Item1 cost?5
Please enter the name of product 2:Item2
How much does Item2 cost?5
The total cost of your items is 10
Ad
source: stackoverflow.com
Ad