[英]Python - how to add integers (possibly in a list?)
I'm doing an assignment for school, I'm up to a part where i have to have the 'User' input a list of integers, the program must then add the integers in the list together and return:我正在为学校做作业,我必须让“用户”输入一个整数列表,然后程序必须将列表中的整数相加并返回:
Total: $[sum of integers]
as of yet, i have到目前为止,我有
cost = input("Enter the expenses: ")
cost = int(cost)
total = sum(i)
print("Total: $" + i)
but it keeps returning the error:但它不断返回错误:
Traceback (most recent call last):
File "C:\Python33\Did I Spend Too Much.py", line 2, in <module>
cost = int(cost)
ValueError: invalid literal for int() with base 10: '10 15 9 5 7'
Where '10 15 9 5 7' are the integers I entered in testing.其中“10 15 9 5 7”是我在测试中输入的整数。
Any help with this would be greatly appreciated对此的任何帮助将不胜感激
cost = cost.split()
total = sum([ int(i) for i in cost ])
You have to parse the string.你必须解析字符串。
input
returns you string as 10 15 9 5 7
so parse that string with input
将您的字符串返回为10 15 9 5 7
所以用(space) and you will get list of
str
. (空格),您将获得
str
列表。 Convert list of str
to int
and do sum.将
str
列表转换为int
并求和。
I can give you solution, but best way you tried your self as student.我可以给你解决方案,但最好的方式是你作为学生尝试过自己。 If got any problem, give comments.
如果有任何问题,请发表评论。
You must first convert the string into a list of integers as follows:您必须首先将字符串转换为整数列表,如下所示:
cost = cost.split()
cost = [int(i) for i in cost]
and then you can call sum(cost)
然后你可以调用
sum(cost)
You are trying to convert blank spaces to integers as well which is something that is not possible.您还试图将空格转换为整数,这是不可能的。 Instead you need to split the string and then convert all individual elements to ints :)
相反,您需要拆分字符串,然后将所有单个元素转换为整数 :)
cost = cost.split()
cost = [ int(i) for i in cost ]
total = sum(total)
您输入的“10 15 9 5 7”无法识别为整数,因为其中有空格,也无法识别为整数列表,您需要进行一些“转换”。
This is my answer这是我的回答
expenses = input("Enter the expenses: ")
expenses = expenses.split()
total = 0
for expense in expenses:
total += int(expense)
print("Total: $" + str(total))
You need to remove spaces.您需要删除空格。 I am pretty sure commas also work!
我很确定逗号也有效!
[10, 2, 20] # Example [10, 2, 20] # 示例
Or: [10220]或:[10220]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.