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不能添加到这个列表中,但是我不是试图添加整数吗?
答案 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
。