0

I am creating a list to store integers until the user hits 'N'.

I need the code to sum all the integers in the list. However, I have to get an error in the code.

The error is

sumlst = sum(lst)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

How do I fix it?

Here's my code:

print("Enter an integer or N to exit:")
lst=[]

while True:
    data = input()
    if data == "N":
        break
    lst.append(data)

sortlst = sorted(lst)
sumlst = sum(lst)

print (sortlst)
print (sumlst)
mhhabib
  • 2,975
  • 1
  • 15
  • 29
  • 3
    You're appending a string to the list but want to get an integer sum that's why you're getting the error. Use instead `lst.append(int(data))` – mhhabib Feb 06 '21 at 15:41
  • Read the error. What is it saying? + (from sum) doesn't work between ints and strs. Makes sense. So either filter out your strings, or make sure the data entered is a float or int. – likethevegetable Feb 06 '21 at 15:45
  • @likethe Does it make sense? In the code given, int types are never added to the list – OneCricketeer Feb 06 '21 at 15:48
  • Then you need to convert them to int, as @toRex points out. By default, input will take str – likethevegetable Feb 06 '21 at 15:52
  • Thank you for the advice and help! toRex and likethevegetable . I have just started learning Python and I am still trying to get use to all these. Sorry for posting a new question on this. – ZephrylOOO Feb 06 '21 at 16:05
  • This question has been closed saying that answer is available in some other [question](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers), however that asks for input as integer which is bound to fail with `ValueError: invalid literal for int() with base 10: 'N'` when you give input a 'N'. Hence comment by @toRex is the correct answer. – AmitP Feb 06 '21 at 16:17

0 Answers0