I tried to create a tic tac toe program with python list:
theBoard=[' '' '' ']*3
def userInput(board):
loop=True
while loop:
userInput=input("Please enter (row,column)")
row=int(userInput[0])
column=int(userInput[2])
if row<1 or row>3:
print('[ERROR: Invalid Input]')
loop=True
elif column<1 or column>3:
print('[ERROR: Invalid Input]')
loop=True
else:
board[row-1][column-1]='X'
loop=False
def drawBoard(board):
#Function that prints out board
print(board[0][0] ' | ' board[0][1] ' | ' board[0][2])
print('---------')
print(board[1][0] ' | ' board[1][1] ' | ' board[1][2])
print('---------')
print(board[2][0] ' | ' board[2][1] ' | ' board[2][2])
print('---------')
userInput(theBoard)
drawBoard(theBoard)
Error I got: TypeError: 'str' object does not support item assignment
edit: sorry, i forgot to add the error line
I dont know why but the program mistook theBoard as a string rather than a list.
*A lot of people asked me to change theBoard=[' '' '' ']*3 to theBoard=[' ',' ',' ']*3 which i did however, I am still receiving the same error
CodePudding user response:
In the line
theBoard=[' '' '' ']*3
You are creating a list of size 9
in the line
board[row-1][column-1]
You are treating the list as if it is a 2d list
To make theBoard
in to a 2d list try:
theBoard=[' ',' ',' ']
theBoard = [theBoard,theBoard,theBoard]
CodePudding user response:
Well, its not the program, it
s you who mistook string for a list. You declare the board as:
theBoard=[' '' '' ']*3
So, youre passing a single string (technically three strings, but passed as one, so for your comfort, they
re concatenated). Output is a list with three strings.
Therefore, when you call theBoard[0][1] - you are trying to access the second character of the first string. And that is ok, but, as strings are immutable, changing it is not allowed.
Declaring board like below is pretty much what you wanted, but it still gives you one dimentional table (thereforo, you should access the last element by calling theBoard[8], and not theBoard[2][2]
theBoard=[' ',' ',' ']*3
If you want it to be two dimensional, try:
theBoard = [["","",""] for i in range(3)]