Reputation: 135
Hi I have just started an online course for python, just for me, and one of the exercises is asking me to add the first and list integer from a list you input, I think I have it, but not too sure as it keeps giving me an error,
ValueError: invalid literal for int() with base 10
my code is
userList = list(map(int, input().split(',')))
intTotal = userList[1] + userList[len userList]
print (intTotal)
now, how I understand it the, [1] would be the first userList value, as it is the first position in the list, and the [len userList] should give me last position as it is giving the length of list as position number.
then it should print the variable intTotal
If you could show me where i am going wrong if it all that would be ace!
Upvotes: 0
Views: 2243
Reputation: 51175
Your error is most likely that your input is something like 1, 2, 3, 4, 5,
When you use split(',')
on this, you will have an extra empty entry at the end of your list that you must account for. You can check for this in a list comprehension.
To access the last element of the list, you may use arr[len(arr)-1]
, or in Python which supports negative indexing, arr[-1]
.
Here is a working version of your code with the above changes made:
userList = [int(x.strip()) for x in input().split(',') if x]
intTotal = userList[0] + userList[-1]
print (intTotal)
Sample run:
>>>1, 2, 3, 4, 5,
6
You could make this even more robust to filter out bad input by using isdigit()
, which would allow for the user to enter letters, but it would only add the first and last numbers entered:
userList = [int(x) for x in input().split(',') if x.isdigit()]
Sample run:
>>> 1,2,a,3,4,6,b,4
5
Upvotes: 3