【问题标题】:Trying to print(sum(list)) but getting error TypeError: unsupported operand type(s) for +: 'int' and 'str'尝试打印(总和(列表))但收到错误类型错误:+ 的不支持的操作数类型:'int' 和 'str'
【发布时间】:2020-05-23 17:12:38
【问题描述】:

我正在尝试对其中只有整数的列表求和,但在第 22 行出现错误 TypeError: unsupported operand type(s) for +: 'int' and 'str'。这是一个 '石头剪刀布游戏

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

【问题讨论】:

    标签: python list sum


    【解决方案1】:

    您没有将整数附加到数组中。相反,您正在附加带有整数值的字符串!

    您应该执行以下操作:

    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
    

    【讨论】:

      【解决方案2】:

      您使用score.append("1"),将字符串添加到列表中。然后,您使用sum(score),它不能工作,因为它现在包含一个字符串。使用score.append(1)

      【讨论】:

        【解决方案3】:

        您将字符串附加到列表score.append('1') 这里'1' 是一个字符串,而不是score.append(1)

        【讨论】:

          猜你喜欢
          • 2014-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-27
          • 2013-10-12
          • 2018-02-05
          • 1970-01-01
          相关资源
          最近更新 更多