python - 如何将运行总计相加?
问题描述
我有一个家庭作业任务,基本上是创建一个超市结账程序。它必须询问用户他们有多少物品,然后他们输入物品的名称和成本。这一点我做得很好,但是我无法将总数加在一起。
最后一行代码没有将价格加在一起,它只是列出了它们。
到目前为止的代码
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
推荐阅读
- javascript - 访问 alpnProtocol 属性时的 Node.js req vs req.stream.session
- python - Python Matplotlib Taylor 系列图形线不起作用
- powerbi - 将Teradata代码导入PowerBI,PowerBI不能接受双引号
- typescript - 动态加载 TabPanel 项内容 ext.js 5.1.3
- python - 在某个部分中查找多个正则表达式匹配项
- c++ - 将文件保存为当前登录用户
- python - 尝试删除每个单词的标点符号列表 - 最终删除所有标点符号
- foreign-keys - 具有外键的数据库:描绘前向与后向关系的好方法?
- xamarin - Xamarin:修复链接器错误(使用 FFImageLoading 和 SDWebImage)
- linux - 如何改进(缩短时间)我的 shell 脚本代码?我正在尝试将文件夹分成几个较小的文件夹