Skip to content Skip to sidebar Skip to footer

What's Causing This Variable Referenced Before Assignment Error?

This is the code that I am working with: import pygame global lead_x global lead_y global lead_x_change global lead_y_change lead_x = 300 lead_y = 300 lead_x_change = 0 lead_y_ch

Solution 1:

Python's handling of "global" variables is indeed a bit weird, especially if you're not accustomed to it.

The simple fix for your problem is to move your global declarations inside each function that uses those variables. So:

def playerUpdateMovement():
    global lead_x
    global lead_y
    global lead_x_change
    global lead_y_change

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        lead_x_change = -1

This tells Python that your use of lead_x_change within the playerUpdateMovement function is actually a reference to a global variable, and not a use of a local variable (of the same name), which is the default treatment.

Solution 2:

If you need to modify a global variable from inside a function you need to use the global keyword: global lead_x in this case, before any assignment

Solution 3:

Python doesn't need global variables declared in any special way. Just declare and initialize your variables at the top like you did in the second chunk of code. Then move your global declarations to inside each method that CHANGES your global. So you can cut your first chunk and paste into your method.

Note that to READ a global you don't need to use the global keyword. This can help keep your constants constant, since Python doesn't handle constants specially.

Post a Comment for "What's Causing This Variable Referenced Before Assignment Error?"