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不能添加到此列表中,但是我不是要添加整数吗?

最佳答案

有两个问题:您假设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≙Python 2的raw_input

10-06 06:14