I have been trying to write a Python script that uses global variables. I am getting what seems to be unexpected results in my code. Instead of dumping all the code here, I have created a small piece of code to show what I'm seeing.
def func1():
global aaa
aaa = 1
def func2():
while aaa < 5:
print(aaa)
aaa += 1
func1()
func2()
I am expecting to get,
1
2
3
4
What I get instead is,
Traceback (most recent call last):
File "test2.py", line 11, in <module>
func2()
File "test2.py", line 6, in func2
while aaa < 5:
UnboundLocalError: local variable 'aaa' referenced before assignment
If I change func2 to remove the while loop & just print the aaa variable, it works fine, so the global variable is accessible.
def func1():
global aaa
aaa = 1
def func2():
print(aaa)
func1()
func2()
Running it produces,
1
If I set the aaa value at the top of func2 it also works.
def func1():
global aaa
aaa = 1
def func2():
aaa = 1
while aaa < 5:
print(aaa)
aaa += 1
func1()
func2()
Which results in,
1
2
3
4
I have experience with Perl, but am new to Python. Is there something that I'm missing here?