Reputation: 1
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?
Upvotes: 0
Views: 249
Reputation: 11645
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
Upvotes: 2
Reputation: 11837
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.
Upvotes: 2