14

I don't know why when a is located in def test() it can not be found and gives the error

UnboundLocalError: cannot access local variable 'a' where it is not associated with a value

import keyboard
import time

a = 0

def test():
    a+= 1
    print("The number is now ", a)
    time.sleep(1)

while keyboard.is_pressed('i') == False:
    
    test()

I tried setting a as global a or using a nonlocal modifier on it inside the def but it doesn't seem to work. Is there a way I can get it to recognize a and run properly?

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
Oliver Sklar
  • 151
  • 1
  • 1
  • 3

3 Answers3

11

Python variables are scope based. This means one cannot access a value declared inside a function. But you can access a variable declared outside a function.

This would fail:

def func():
    a = 1

func()
print(a)

this would print 1:

def func():
    print(a)

a = 1
func()

Notice you can access it. You'll fail if you want to update it.

This would fail too:

def func():
    a = a + 1
    print(a)

a = 1
func()

What you need is no tell the interpreter to find variable a in the global scope.

def func():
    global a
    a = a + 1
    print(a)

a = 1
func()

Warning: It's not a good practice to use global variables. So better make sure the function is getting the value.

def func(a):
    a = a + 1
    print(a)

a = 1
func(a)
MSH
  • 1,743
  • 2
  • 14
  • 22
3

To access a global variable within a function you must specify it with global. Otherwise, the variable inside the function is a local variable that only has utility inside that function. That's why you get the error: "UnboundLocalError: local variable 'a' referenced before assignment". Inside the function you haven't defined the variable 'a' yet, either local or global.

import keyboard
import time

a = 0

def test():
    global a
    a+= 1
    print("The number is now ", a)
    time.sleep(1)

while keyboard.is_pressed('i') == False:
    
    test()
José Juan
  • 66
  • 4
2

You need to pass a to the function test. Python thinks as the a in the function as a local variable. This will work:

import keyboard
import time
a = 0
def test(a=a):
    a+= 1
    print("The number is now ", a)
    time.sleep(1)
while keyboard.is_pressed('i') == False:
    test()
Remzinho
  • 538
  • 2
  • 9