“cannot access local variable ‘a’ where it is not associated with a value”, but the value is defined [duplicate]

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()

You need to 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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)