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

Issue

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

Solution

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published