我正在为学校做作业,我需要让“用户”输入一个整数列表,然后程序必须将列表中的整数相加并返回:
Total: $[sum of integers]
到目前为止,我有
cost = input("Enter the expenses: ")
cost = int(cost)
total = sum(i)
print("Total: $" + i)
但它一直返回错误:
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'
其中 '10 15 9 5 7' 是我在测试中输入的整数。
如有任何帮助,我们将不胜感激
最佳答案
cost = cost.split()
total = sum([ int(i) for i in cost ])
关于Python - 如何添加整数(可能在列表中?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22526799/