首页 > 解决方案 > 如何将运行总计相加?

问题描述

我有一个家庭作业任务,基本上是创建一个超市结账程序。它必须询问用户他们有多少物品,然后他们输入物品的名称和成本。这一点我做得很好,但是我无法将总数加在一起。

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

到目前为止的代码

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 的家庭作业,但由于某种原因我被难住了!

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

标签: pythonpython-2.x

解决方案


您必须遍历列表以求和总数:

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

推荐阅读