0

In this code:

# other variables defined above
global movex
movex = 0
global movey
movey = 0
def wasd(event):
    key = event.char
    if key == 'w':
        movey = -5
    elif key == 'a':
        movex = -10
    #elif key == 's':
        #movey = 10
    elif key == 'd':
        movex = 10
    p.moverect(movex,movey)
tk.bind('<Key>', wasd)
tk.bind('<Key>', wasd)
largetext = Font(size=13)
p = player(sx1=950,sy1=520,sx2=975,sy2=545)

it says error because I referenced the local variables movex and movey (in different cases), before defining them. How did this happen if I defined the variables movex and movey as global variables?

I also tried not using the global keyword, but I get the same error.

user14354511
  • 55
  • 1
  • 5
  • Because you assign to it. The global keyword needs to be _inside_ the function. – jonrsharpe Oct 24 '21 at 14:25
  • Does this answer your question? [referenced before assignment error in python](https://stackoverflow.com/questions/855493/referenced-before-assignment-error-in-python) – Gino Mempin Oct 24 '21 at 14:26

1 Answers1

0

As explained by @jonrsharpe global is to be invoked inside of a function.

# other variables defined above
movex = 0
movey = 0
def wasd(event):
    global movex
    global movey

    key = event.char
    if key == 'w':
        movey = -5
    elif key == 'a':
        movex = -10
    #elif key == 's':
        #movey = 10
    elif key == 'd':
        movex = 10
    p.moverect(movex,movey)
tk.bind('<Key>', wasd)
tk.bind('<Key>', wasd)
largetext = Font(size=13)
p = player(sx1=950,sy1=520,sx2=975,sy2=545)
James Hirschorn
  • 7,032
  • 5
  • 45
  • 53