0
while True:
   get2=input('Enter: ')
   lst2.append(get2)
   if get2=='':
       break

TypeError: unsupported operand type(s) for +: 'int' and 'str' occurs. I think this is because the '' for the exit command is not recognized as a integer. How do I '', the enter key, as the exit code AND make sum(list) function work?

1
  • You probably want to check the input value before you append it to the list. Commented Apr 3, 2016 at 16:37

2 Answers 2

2

The result of input in Python 3 is always a string. The sum function is then trying to add each item of the list together, starting with 0, so it attempts to to this:

0 + your_list[0]

But, the first item of your list is a string, and you can't add an integer to a string.

To get around this, convert the input to an integer first by using the int function:

print('Enter a series of integers. Hit enter to quit')
lst1=[]
lst2=[]

while True:
    get1=input('Enter: ')
    if get1=='':
        break
    lst1.append(int(get1))



while True:
   get2=input('Enter: ')
   if get2=='':
       break
   lst2.append(int(get2))


if sum(lst1)==sum(lst2):
   print('The two lists add up the same')
else:
   print('The two lists do not add up')

Note that I've moved the if statements before the integer conversion, because otherwise entering '' will cause an exception to be thrown as an empty string isn't a valid integer.

Sign up to request clarification or add additional context in comments.

1 Comment

@Din No problem. Please remember to accept answers that have helped you!
2

You're appending a string and then trying to sum a bunch of strings togethers.

You need to convert them to integers / floating point numbers first so you'd have lst2.append(int(get2)) and lst1.append(int(get1))

or you could use float for floating point numbers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.