列表的TypeError的未知原因

时间:2016-11-19 19:47:32

标签: python python-3.x

def player_move(Player, board):
    playerMarker = None
    print("Player ",Player," it is your turn!")
    playerChoice = input("Please input your move: ")
    if Player == 1:
        playerMarker == 9
    else:
        playerMarker == 10
    board[playerChoice] == playerMarker

这会产生TypeError:

line 36, in player_move
board[playerChoice] == playerMarker
TypeError: list indices must be integers or slices, not str

为什么会这样,我怎么能阻止这种情况发生?我理解str不能添加到这个列表中,但是我不是试图添加整数吗?

1 个答案:

答案 0 :(得分:1)

有两个问题:你假设playerChoice是一个整数(它是一个字符串,必须使用int()转换。*),并且你使用==进行分配。这是固定的:

def player_move(Player, board):
    playerMarker = None
    print("Player ",Player," it is your turn!")
    # should probably check for invalid inputs here
    playerChoice = int(input("Please input your move: "))
    if Player == 1:
        playerMarker = 9
    else:
        playerMarker = 10
    board[playerChoice] = playerMarker

*您可能会对来自Python 2感到困惑,其中input确实(偶尔)返回一个整数; Python 3的input≙Python2的raw_input