如何将 运行 加在一起?

How to add a running total together?

我有一个家庭作业任务,主要是创建一个超市结账程序。它必须询问用户他们有多少件物品,然后他们输入物品的名称和价格。这一点我已经很好地解决了,但是我无法将总数加在一起。

最后一行代码没有将价格相加,只是列出它们。

到目前为止的代码

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

这是我正在做的 SKE 的家庭作业任务,但由于某种原因我被难住了!

预期的输出是在程序结束时,它将显示添加到程序中的项目的总成本,并带有 £ 符号。

您必须遍历列表来求和:

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

备选方案(对于 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))

输出:

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

您需要将费用申报为 int 并求和:

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

grocerylist = []
costs = []

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.append(int(itemcost))

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

raw_input 似乎也有问题。我把它改成 input.