I am writing some simple game in Python 3.4. I am totally new in Python. Code below:
def shapeAt(self, x, y):
return self.board[(y * Board.BoardWidth) + x]
Throws an error:
TypeError: list indices must be integers, not float
For now I have found that this may happen when Python "thinks" that list argument is not an integer. Do you have any idea how to fix that?
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
Convert Input to Number in Python 2. x has two built-in functions for accepting user input. the raw_input() and input() . The input() function is intelligent as it judges the data type of data read, whereas the raw_input() always treats the input as a string. So, always use the input() function in Python 2.
To declare an int variable in C++ you need to first write the data type of the variable – int in this case. This will let the compiler know what kind of values the variable can store and therefore what actions it can take. Next, you need give the variable a name. Lastly, don't forget the semicolon to end the statement!
int((y * Board.BoardWidth) + x)
use int
to get nearest integer towards zero.
def shapeAt(self, x, y):
return self.board[int((y * Board.BoardWidth) + x)] # will give you floor value.
and to get floor value use math.floor
(by help of m.wasowski)
math.floor((y * Board.BoardWidth) + x)
If x
, y
are numbers or strings representing number literals you can use int
to cast to integer, while floating point values get floored:
>>> x = 1.5
>>> type(x)
<type 'float'>
>>> int(x)
1
>>> type(int(x))
<type 'int'>
This is probably because your indices are of type float
where these should be ints
(because you are using them as array indices). I wouldn't use int(x)
, I think you probably intended to pass an int
(if not, use return self.board[(int(y) * Board.BoardWidth) + int(x)]
of course).
You may also want to get floor value to get your index and here is how to do it:
import math
def shapeAt(self, x, y):
return self.board[math.floor((y * Board.BoardWidth) + x)]
You can also use Python's type()
function to identify type of your variables.
what is the type of x and y you need to check that, then convert them to integer type using int
:
def shapeAt(self, x, y):
return self.board[(int(y) * Board.BoardWidth) + int(x)]
if you want to first store them:
def shapeAt(self, x, y):
x,y = int(x),int(y)
return self.board[(y * Board.BoardWidth) + x]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With