Python 如何将运行总数相加?

Python 如何将运行总数相加?,python,python-2.x,Python,Python 2.x,我有一个家庭作业,主要是创建一个超市结账程序。它必须询问用户他们有多少物品,然后他们输入物品的名称和成本。这一点我做得很好,但是我在把总数加起来时遇到了麻烦 最后一行代码没有把价格加在一起,只是列出了它们 迄今为止的代码 print "Welcome to the checkout! How many items will you be purchasing?" number = int (input ()) grocerylist = [] costs = [] for i in rang

我有一个家庭作业,主要是创建一个超市结账程序。它必须询问用户他们有多少物品,然后他们输入物品的名称和成本。这一点我做得很好,但是我在把总数加起来时遇到了麻烦

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

迄今为止的代码

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


您需要将您的成本声明为
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)))

原始输入似乎也有问题。我把它改成了
input

python2和python3?这是什么?@BlackThunder Python 2,考虑到我在Python 3中不再定义的
raw_input
的存在,
raw_input
的“问题”是,它在Python 3中不存在(它被重命名为input),还有一点改进建议:使用实际的字符串格式,而不是
“…+str(…)
(OP的代码中没有它,但这并不意味着它不能改进;))太棒了,谢谢你!很抱歉,这个问题在某些方面有点模糊,第一次在这里发布!
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
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)))