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
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.
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.
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.
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.
cost = cost.split()
total = sum([ int(i) for i in cost ])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With