+ 2
I was reading python Documentation. Will you please explain this paragraph? Please
The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables and variables of enclosing functions cannot be directly assigned a value within a function (unless, for global variables, named in a global statement, or, for variables of enclosing functions, named in a nonlocal statement), although they may be referenced.
2 Réponses
+ 2
I'm not too sure what a symbol table is, but I think what it's basically saying is that global variables can be referenced (like in print(x)) in a function, but not assigned a value within it (like x = 98). If you try to access a variable that was not assigned a value within the function you're trying to access it in, it will look at the global variables. If you try to assign a value to a global variable inside a function, it will create a new local variable. Thus, you cannot assign a value to a global variable from within a function. See the following example:
# Note that the functions do not have parameters
def f():
x = 98
y = 99
z = 100
print(x, y, z)
return
def h():
print(x, y, z)
return
x = 1
y = 2
z = 3
# x, y, and z here are global variables.
h()
>>> 1 2 3
# h() prints the values of global variables x, y, and z because it doesn't have any local variables named x, y, and z.
f()
>>> 98 99 100
# f() assigned values to its own local variables x, y, and z.
# The print statement in f() prints 98 99 100 because it looks at the local variables (I guess symbol table as you said) first and sees that there are in fact local variables x, y, and z.
h()
>>> 1 2 3
# f() cannot modify the global variables, so h() still prints 1 2 3.
+ 1
Zerokles thanks for your help. I understood it now.