4

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

0

6 Answers 6

4
cost = cost.split()
total = sum([ int(i) for i in cost ])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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)

Comments

1

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)

3 Comments

Not quite. You have to call int on each element in the list, so you use map.
total = sum( [int(c) for c in cost.spit()] )
You can drop the brackets.
1

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

Comments

0

"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".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.