Reputation: 259
I am trying to write a function which enables a move 1 unit to the left (in the x-axis) in a grid. It should only work if there is a valid coordinate to the left, and if not (i.e. the start point is on the edge of the grid), the function should return None
. Here is my attempt:
def left_move(point):
try:
LEFT = grid[point[1]][point[0]-1]
except IndexError:
return None
if LEFT == '.':
change = [-1,0]
for idx, amount in enumerate(change):
point[idx]+=amount
return point
return None
Say the starting point is [0,3]
and therefore on the edge of the grid and I only run the top part of the code:
def left_move(point):
try:
LEFT = grid[point[1]][point[0]-1]
except IndexError:
return None
It returns None
as expected. But if the whole block is executed it returns [-1,3]
which is outside of the grid and shouldn't be allowed by the try-except
. Why is this? And how can it be corrected?
Upvotes: 1
Views: 94
Reputation: 1914
Here, you need to place the rest of the code inside the try statement. Otherwise, it will try, fail, and then run the rest of the code.
def left_move(point):
if point[0]-1 != -1:
LEFT = grid[point[1]][point[0]-1]
if LEFT == '.':
change = [-1,0]
for idx, amount in enumerate(change):
point[idx]+=amount
return point
return None
else:
return None
Upvotes: 2
Reputation: 2936
This is because Python's interpretation of -1
in array indexing is the last element of the array. -1
is a legal way of referencing array elements and thus will not trigger an IndexError
exception.
>>> a = [0,1,2]
>>> print a[-1]
2
You would need to manually check if the value you are given resolves to -1
and then handle that accordingly.
Upvotes: 2