I messed up several times while implementing it in python, so make a note for myself. It's understandable that this code returns the following result:
x = 1
def func1():
print(x)
def func2():
x = "hoge"
print(x)
func1()
func2()
>>> 1
>>> hoge
In python, when referencing a variable, it goes to refer to the global scope if it is not declared inside the local scope.
Also, if the variable is not declared before rewriting the variable in the local scope, an error is returned.
def func3():
y += 1
y = 5
print(y)
func3()
>>> Traceback (most recent call last):
>>> File "/test.py", line 8, in <test>
>>> func3()
>>> File "/test.py", line 4, in func3
>>> y += 1
>>> UnboundLocalError: local variable 'y' referenced before assignment
I understood it so far, but when global variables were involved, I was immediately confused. In other words, when you operate a variable that is declared as a global variable, you have to declare it explicitly, and an error is usually returned.
x = 1
def func4():
x += 1 #You can't see x yet at this point
x = 5 #At this stage the variable x is added to the local scope
print(x)
func4()
>>> Traceback (most recent call last):
>>> File "/test.py", line 8, in <test>
>>> func4()
>>> File "/test.py", line 4, in func4
>>> x += 1
>>> UnboundLocalError: local variable 'x' referenced before assignment
The solution is simple, and when you use a global variable, let's make it clear that it is a global variable.
x = 1
def func5():
global x #Explicitly be a global variable
x += 1
print(x)
def func6():
x = 10 #Explicitly be a local variable
x += 1
print(x)
func5()
func6()
>>> 2
>>> 11
Recommended Posts