The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function. To solve the error, mark the variable as global in the function definition, e.g. global my_var .
The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.
In order for you to modify test1
while inside a function you will need to do define test1
as a global variable, for example:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
However, if you only need to read the global variable you can print it without using the keyword global
, like so:
test1 = 0
def testFunc():
print test1
testFunc()
But whenever you need to modify a global variable you must use the keyword global
.
Best solution: Don't use global
s
>>> test1 = 0
>>> def test_func(x):
return x + 1
>>> test1 = test_func(test1)
>>> test1
1
You have to specify that test1 is global:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With