Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading