Home > Back-end >  Python says a variable is undefined even though it's clearly defined
Python says a variable is undefined even though it's clearly defined

Time:06-11

I was making a game in Pygame, and I was making a variable that was used in the update function, but it says it's undefined. I've looked it up so much, but couldn't find anybody having the same problem:

# Code Vars
SIN_COUNTER = 0

# Code
def update():
    SIN_COUNTER  = 8
    SIN_COUNTER = math.sin(SIN_COUNTER)

EDIT: I've used other variables that I've declared earlier in the script and they worked.

EDIT #2: The error is UnboundLocalError: local variable 'SIN_COUNTER' referenced before assignment

CodePudding user response:

Well, the interpreter is not wrong. There is indeed no local variable named SIN_COUNTER, only a global one. You have to explicitly declare within the function's context that the symbol SIN_COUNTER refers to a global object:

SIN_COUNTER = 0

def update():
    global SIN_COUNTER
    SIN_COUNTER  = 8
    SIN_COUNTER = math.sin(SIN_COUNTER)
  • Related