Python says a variable is undefined even though it's clearly defined

Question:

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

EDIT #3: Please don’t get mad at me. I’m new to Pygame and just Python in general.

Asked By: BigmancozmoPlayz

||

Answers:

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)
Answered By: Havenard
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.