0

I am attempting to write a list that is a "." at each index for as many times as there are supposed to be rows and columns in my game board. This is the code I am using, but the error I am getting is telling me that I cannot multiply the sequence by a non-int of type 'str'. I am using python 3.5.2.

def mkBoard(rows,columns):
    board = ["."] * rows * columns
    return board

#Take user input for number of rows and columns for the board and converts them into integers
rows = input('Enter the number of rows:')
int(rows)
columns = input('Enter the number of columns:')
int(columns)

#Create the board
board = mkBoard(rows,columns)
dff
  • 311
  • 2
  • 17

2 Answers2

4

You're very close.

You just need to assign the new int values to variables. int() doesn't change the variable, only return a new value.

Therefore, to get the proper rows value use:

rows = int(rows)

and the same for columns

As an aside, You should also look at how you're generating your board. You probably want something like [[".","."], [".", "."]] for a 2x2 board. I advise you look at list comprehensions

Luke K
  • 865
  • 6
  • 13
1

You have another problem in your code which the other answer has not addressed.

>>> ['.'] * 5 * 5
['.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.']

Your board initialization creates a flat list, which is presumably not what you want. Typically you would use a list of lists for this. However, using the overloaded multiplication is a very bad way to create a list of lists:

>>> [['.'] * 5] * 5
[['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.']]

Because now:

>>> board = _
>>> board[0][0] = 'hi'
>>> board
[['hi', '.', '.', '.', '.'], ['hi', '.', '.', '.', '.'], ['hi', '.', '.', '.', '.'], ['hi', '.', '.', '.', '.'], ['hi', '.', '.', '.', '.']]

Every row is a copy of the same list. You should prefer a list comprehension instead:

>>> board = [['.' for row in range(5)] for col in range(5)]
>>> board
[['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.']]
>>> board[0][0] = 'hi'
>>> board
[['hi', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.']]
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82