Function Within A Function Issue
I am a Python and general programming noob. Only been programing for about 2 weeks. I have I quick question regarding functions in python. Can someone explain to why this works: im
Solution 1:
Let's look at a more simplistic example:
def func1():
a = 0
def func2():
print(a)
locals()['a'] = 1print(a)
func2()
func1()
print(a)
This outputs
0
0
1
i.e. the variable a
local to both functions is not modified. Looking at the documentation of locals
one can find that "... changes may not affect the values of local and free variables used by the interpreter." Thus using it to change the value of local variables may or may not work ...
Instead I'd suggest to use a dictionary if you want to associate values with a name:
deffunc1():
d = {'a' : 0}
deffunc2():
print(d['a'])
d['a'] = 1print(d['a'])
func2()
func1()
print(d['a'])
which leads to the following output:
11
Traceback (most recent call last):
File "...", line 10, in <module>
print(d['a'])
NameError: name 'd' is notdefined
The exception caused by the last line is the correct behaviour since d
is only defined within func1
. It therefore isn't accessible outside of the scope of func1
.
You can read more about scopes e.g. here.
Post a Comment for "Function Within A Function Issue"