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)) 
3

1 Answer

I find several problems in your code:

  • When you call it, in this line: print(get_position_in_direction(position, direction)), position and direction are not defined
  • The parameters direction and position are useless as input for the function, because you update them afterwards, so let's remove the lines where you update them
  • In the if-else statements there is a misspelling, you wrote direcrion instead of direction.
  • 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, xi and yi will 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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.