0

I was trying to make a tic tac toe game and thought that it is better to make a matrix and then ask user to where to put 0 or X. My code is like this. (since I could not find how to make an empty matrix in python)

 board = [[1,1,1], [1,1,1], [1,1,1]]

print board

mark1 = raw_input("enter 0 or X: ")

r = raw_input("now enter row: ")

c = raw_input("now enter col: ")


board [r] [c] = mark1

print board

but board[r][c] is wrong because it says:

 board [r] [c] = mark1

TypeError: list indices must be integers, not str

Any solution or better way for me to approach this ?

thank you !

Ash
  • 261
  • 4
  • 16
  • 2
    you need to convert the input into integers, with `int(r)` – PRMoureu Sep 04 '17 at 18:16
  • or you can use `input()`, for `r` and `c`, instead of `raw_input()` to get number as `int`... – Dadep Sep 04 '17 at 18:20
  • thanks.. it worked. @Dadep – Ash Sep 04 '17 at 18:23
  • 2
    @Ash have in mind that from security perspective `input` shouldn't be used since it's vulnerable to code injection since it evaluates the input (e.g. `__import__("os").system('ls')` will be executed). You should better follow @PRMoureu's advice – coder Sep 04 '17 at 18:31

1 Answers1

0

The function raw_input return strings not int, but list index must be int you can do like this:

board = [[1,1,1], [1,1,1], [1,1,1]]    
print board    
mark1 = raw_input("enter 0 or X: ")    
r = raw_input("now enter row: ")    
c = raw_input("now enter col: ")   
board [int(r)] [int(c)] = mark1    
print board

My English is not good, I hope you can understand.

wittich
  • 2,079
  • 2
  • 27
  • 50
G.Thing
  • 1
  • 1