Reputation: 79
I'm trying to sum a list which has only integers in it, but I'm getting error TypeError: unsupported operand type(s) for +: 'int' and 'str' in line 22. This is a 'rock paper scissors' game
import random
import time
score = []
while True:
print('r/p/s')
x=input('You: ')
y=random.randint(1,3)
if str(y) == '1':
print('CPU: r')
elif str(y) == '2':
print('CPU: p')
elif str(y) == '3':
print('CPU: s')
if x == 'r' and str(y) == '3' or x == 'p' and str(y) == '1' or x == 's' and str(y) == '2':
print('WIN')
score.append('1')
print('SCORE:',end='')
print(sum(score))
elif x == 'r' and str(y) == '1' or x == 'p' and str(y) == '2' or x == 's' and str(y) == '3':
print('TIE')
elif x == 'r' and str(y) == '2' or x == 'p' and str(y) == '3' or x == 's' and str(y) == '1':
print('LOSS')
if input('again? (y/n) ') == 'y':
continue
else:
print(' -------- ')
print('THANKS FOR PLAYING!')
print(' -------- ')
time.sleep(2)
break
Upvotes: 0
Views: 204
Reputation: 933
You are appending string to list score.append('1')
here '1' is a string do this instead score.append(1)
Upvotes: 1
Reputation: 797
You are not appending integers to the array. Instead, you are appending strings with integer values!
You should do the following:
import random
import time
score = []
while True:
print('r/p/s')
x = input('You: ')
y = random.randint(1,3)
if str(y) == '1':
print('CPU: r')
elif str(y) == '2':
print('CPU: p')
elif str(y) == '3':
print('CPU: s')
if x == 'r' and str(y) == '3' or x == 'p' and str(y) == '1' or x == 's' and str(y) == '2':
print('WIN')
score.append(1)
print('SCORE:',end='')
print(sum(score))
elif x == 'r' and str(y) == '1' or x == 'p' and str(y) == '2' or x == 's' and str(y) == '3':
print('TIE')
elif x == 'r' and str(y) == '2' or x == 'p' and str(y) == '3' or x == 's' and str(y) == '1':
print('LOSS')
if input('again? (y/n) ') == 'y':
continue
else:
print(' -------- ')
print('THANKS FOR PLAYING!')
print(' -------- ')
time.sleep(2)
break
Upvotes: 2
Reputation: 272
You use score.append("1")
, adding a string to a list. Then, you use sum(score)
, which cannot work since it now contains a string. Use score.append(1)
Upvotes: 2