我有一项家庭作业,基本上是创建一个超市结帐程序。它必须询问用户它们有多少个项目,然后输入项目名称和成本。这一点我做得很好,但是我很难将总数相加。
最后一行代码不会将价格加在一起,而只是列出价格。
到目前为止的代码
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的一项家庭作业,但是由于某种原因我很沮丧!
预期输出是在程序结束时,将显示添加到程序中并带有£符号的项目的总成本。
答案 0 :(得分:0)
您必须遍历列表以求和:
...
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
答案 1 :(得分:0)
您需要将费用声明为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
。