user3302936
user3302936

Reputation: 45

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

Upvotes: 1

Views: 83

Answers (3)

Maxime Lorant
Maxime Lorant

Reputation: 36161

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]

Upvotes: 2

Mohamed Abd El Raouf
Mohamed Abd El Raouf

Reputation: 928

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)

Upvotes: 1

njzk2
njzk2

Reputation: 39406

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.

Upvotes: 0

Related Questions