Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 858
HERO_OF_ME9848 Avatar asked Mar 20 '14 07:03

HERO_OF_ME9848


People also ask

How to add an integer to an array in Python?

If you are a Python developer or learner then you may be familiar with numpy library. In this library, we have a similar object like list, which is known as array. But an array is different from a list. We can add any integer to each element in an array by using “+” operator. But we can’t do so with a list.

Can you add a specific number to every element in Python?

This Python tutorial will help you to understand how easily you can add a specific number to every element in a list. Let’s understand this with an example first then we will explain our code. This is an example of a list.

How to insert an element in a list in Python?

insert () is an inbuilt function in Python that inserts a given element at a given index in a list. index - the index at which the element has to be inserted. element - the element to be inserted in the list. This method does not return any value but it inserts the given element at the given index.

How do you append values to a list in Python?

Here, case_numbers.append (case_number) statements add the elements to the list. While it's true that you can append values to a list by adding another list onto the end of it, you then need to assign the result to a variable. The existing list is not modified in-place. Like this: However, this is far from the best way to go about it.


2 Answers

cost = cost.split()
total = sum([ int(i) for i in cost ])
like image 177
Anvesh Avatar answered Nov 14 '22 21:11

Anvesh


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.

like image 44
Nilesh Avatar answered Nov 14 '22 23:11

Nilesh