-2

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))
shuberman
  • 1,416
  • 6
  • 21
  • 38
  • 1
    You define position inside the function (line 3) move it outside (line 1 or second to last) – Sayse Aug 15 '19 at 09:11
  • 1
    Possible duplicate of [Short description of the scoping rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – WiseDev Aug 15 '19 at 09:30
  • "i think i have already defined position before call it" Why do you think that? – MisterMiyagi Aug 15 '19 at 10:56

1 Answers1

1

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))
ivallesp
  • 2,018
  • 1
  • 14
  • 21
  • if you enter the `else` block, then `xi, yi` would be undefined. Therefore you could trigger an error still. Also, according to your logic about `direction`, `position might as well be removed as an argument`. – WiseDev Aug 15 '19 at 09:22
  • I completely agree with you. See my updated code. Thanks – ivallesp Aug 15 '19 at 09:30