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?