Python - how to add integers (maybe to a list?)

I am 15 years old, and I am doing the task for school, I get to the part where I need the User to enter a list of integers, the program must then add the integers to the list together and return:

Total: $[sum of integers]

so far i have

cost = input("Enter the expenses: ")
cost = int(cost)
total = sum(i)
print("Total: $" + i)

but he keeps returning an 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 'is the integers I entered when testing.

Any help with this would be greatly appreciated.

+4
source share
5 answers
cost = cost.split()
total = sum([ int(i) for i in cost ])
+2
source

You are also trying to convert spaces to integers, which is not possible. Instead, you need to split the string and then convert all the individual elements to ints :)

cost = cost.split()
cost = [ int(i) for i in cost ]
total = sum(total)
+1

:

cost = cost.split()

cost = [int(i) for i in cost]

sum(cost)

0

. input 10 15 9 5 7, (), str. str int .

, . , .

0

"10 15 9 5 7" , , , "".

0

Source: https://habr.com/ru/post/1532616/


All Articles