Home > front end >  I'm getting a Local variable referenced before assignment even after declaring the variable on
I'm getting a Local variable referenced before assignment even after declaring the variable on

Time:11-07

I'm learning how to code on Python and here's my first code that I learned from a book. I want to add a score every time the user clicks on an apple.

Here's my error:

line 19, in on_mouse_down
    score = score   1
UnboundLocalError: local variable 'score' referenced before assignment

I already declared a variable on top and every time the user clicks on an apple, I'm incrementing the score by 1. After that, I want to print the score to the console. Here's my code:

from random import randint

apple = Actor("apple")
score = 0

def draw():
    screen.clear()
    apple.draw()

def place_apple():
    apple.x = randint(10, 800)
    apple.y = randint(10, 600)
    
    

def on_mouse_down(pos):
    if apple.collidepoint(pos):
        score = score   1
        print(score)
        place_apple()
    else :
        print("You missed!")
        

place_apple()

CodePudding user response:

You need to use the global keyword for this something like this.

def on_mouse_down(pos):
    global score
    if apple.collidepoint(pos):
        score = score   1
        print(score)
        place_apple()
    else :
        print("You missed!")

CodePudding user response:

it's better if you didn't use global variables , but if you must,you should declare it at the first of your function

def on_mouse_down(pos):
    global score
    if apple.collidepoint(pos):
        score = score   1
        print(score)
        place_apple()
    else :
        print("You missed!")
    

CodePudding user response:

There are 4 scopes(a region where the bindings between names and objects hold) in Python:

  • function
  • nonlocal
  • global
  • builtin

In your case, score is declared in global scope while you intend to use it in a function scope, which is not allowed by default.

As others' suggestions, you need to add a global scope inside any function where you want to use it.

For learning Python, realpython is a good resource.

  • Related