Why is it that when I run this code, the error is
'name position is not defined??'
I think I have already defined position before call it
the code is for using r,l,i,d to change the position(x,y)
def get_position_in_direction(position, direction): position=(0,1) x,y=position direction=input("Please enter an action (enter '?' for help): ") if direction=='r': xi,yi=(1,0) elif direcrion=='l': xi,yi=(-1,0) elif direction=='u': xi,yi=(0,1) elif direction=='d': xi,yi=(0,-1) else: pass position=position+xi,yi return position print(get_position_in_direction(position, direction)) 31 Answer
I find several problems in your code:
- When you call it, in this line:
print(get_position_in_direction(position, direction)),positionanddirectionare not defined - The parameters
directionandpositionare useless as input for the function, because you update them afterwards, so let's remove the lines where you update them - In the
if-elsestatements there is a misspelling, you wrotedirecrioninstead ofdirection. - This line does not do what you want to do. See below the way of doing it correctly:
position=position+xi,yi - If you enter a wrong direction,
xiandyiwill be undefined. Let's drop a controlled error in that case
The correct code would be:
def get_position_in_direction(position, direction): x,y=position if direction=='r': xi,yi=(1,0) elif direction=='l': xi,yi=(-1,0) elif direction=='u': xi,yi=(0,1) elif direction=='d': xi,yi=(0,-1) else: raise ValueError("The value specified for the direction" "parameter is not recognised as a valid parameter") position=(position[0]+xi, position[1]+yi) return position position = (0,0) direction = 'l' print(get_position_in_direction(position, direction)) 2