test1 = 0
def testFunc():
test1 += 1
testFunc()
I am receiving the following error:
UnboundLocalError: local variable ‘test1’ referenced before assignment.
Error says that 'test1' is local variable but i thought that this variable is global
So is it global or local and how to solve this error without passing global test1 as argument to testFunc?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
Best solution: Don’t use globals
>>> test1 = 0
>>> def test_func(x):
return x + 1
>>> test1 = test_func(test1)
>>> test1
1
Method 3
You have to specify that test1 is global:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0