HERO_OF_ME9848
HERO_OF_ME9848

Reputation: 47

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.

Any help with this would be greatly appreciated

Upvotes: 4

Views: 5645

Answers (6)

Reed_Xia
Reed_Xia

Reputation: 1442

"10 15 9 5 7" you entered cannot be recognized as an integer since there are spaces in it, and also cannot be recognized as an integer list, you need do some "convert".

Upvotes: 0

Supakorn Ratchadaporn
Supakorn Ratchadaporn

Reputation: 11

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))

Upvotes: 1

Anvesh
Anvesh

Reputation: 617

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

Upvotes: 4

sshashank124
sshashank124

Reputation: 32189

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)

Upvotes: 1

Alex Koukoulas
Alex Koukoulas

Reputation: 996

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)

Upvotes: 1

Neel
Neel

Reputation: 21243

You have to parse the string. input returns you string as 10 15 9 5 7 so parse that string with (space) and you will get list of str. Convert list of str to int and do sum.

I can give you solution, but best way you tried your self as student. If got any problem, give comments.

Upvotes: 1

Related Questions