简体   繁体   中英

Error with the syntax of the list argument

Here is the code I've been working on, a simple Tic Tac Toe game .. I have researched about this error but i could not seem to find the proper solution the code being:

def isSpaceFree(board,move):
     return board[move]==' '


#--------------------------------------------------------------------------

def getPlayerMove(board):
    move=' '
    while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,move):
        print('Your chance,what square do you want to play in ?')
        move=input()
    return int(move)
while gameIsPlaying:
    if turn == 'player':
        # Player's turn.
    drawBoard(theBoard)
    move = getPlayerMove(theBoard)

Error Message:

Traceback (most recent call last):   
File "C:\Python33\FirstTime.py", line 162, in <module>
     move=getPlayerMove(theBoard)   
File "C:\Python33\FirstTime.py", line 82, in getPlayerMove
     while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,move):
File "C:\Python33\FirstTime.py", line 75, in isSpaceFree
     return not board[move]== 'X' or board[move]=='O' TypeError: list indices must be integers, not str

The input function returns a string. So you need to cast the move variable before trying to use it as an list index.

This function should work:

 def isSpaceFree(board,move):
     return board[int(move)]==' '

or even better, with your original isSpaceFree method:

def getPlayerMove(board):
    move = -1  # initialize a 'out of range' number, not an empty string, for consistency
    while move not in range(1, 10) or not isSpaceFree(board,move):
        print('Your chance,what square do you want to play in ?')
        try:
            move = int(input())  # parse number on the fly
        except ValueError:  # if the user doesn't enter a number, display an error
            print('Please enter a number')
            move = -1

    return move

For information:

>>> range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

The problem is in the first value of move which should be integer so you can make it = something like 10 and cast it when calling the function

def getPlayerMove(board):
    move='10'
    while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,int(move)):
        print('Your chance,what square do you want to play in ?')
        move=input()
    return int(move)

move is a string at first ( ' ' ). To use it as an index in a list, you need to use an int. You can cast your string to an int using int(move) .

You should use

move = 0

as initialization, and

while move not in range(1, 10) ...

as a test, since input already returns an int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM