Created by Gökçe Uludoğan
def f():
s = '-- Inside f()'
print(s)
print('Before calling f()')
f()
print('After calling f()')
def f():
s = '-- Inside f()'
print(s)
print('Before calling f()')
f()
print('After calling f()')
Before calling f()
-- Inside f()
After calling f()
def f():
s = '-- Inside f()'
print(s)
print('Before calling f()')
f()
print('After calling f()')
Before calling f()
-- Inside f()
After calling f()
def f():
print('Start f()')
print('End f()')
f()
print("Main program continues")
def f():
print('Start f()')
print('End f()')
f()
print("Main program continues")
Start f()
End f()
Main program continues
def f():
print('Start f()')
print('End f()')
f()
print("Main program continues")
The namespace created for the main program is the global namespace.
When the main program calls f(), Python creates a new namespace for f().
The namespace created for f() is the local namespace.
If your code refers to the name x, Python searches for x in the following namespaces in the order shown:
Search using the LGB rule
def f():
print(x)
x = 'global'
f()
def f():
print(x)
x = 'global'
f()
global
def f():
print(x)
x = 'global'
f()
global
x is defined in only one location.
It’s outside f(), so it's in the global scope
def f():
x = 'local'
print(x)
x = 'global'
f()
def f():
x = 'local'
print(x)
x = 'global'
f()
local
def f():
x = 'local'
print(x)
x = 'global'
f()
local
Line 1 defines x in the global scope.
Line 4 defines x again in the local scope.
According to the LGB rule, the interpreter finds the value from the local space before looking in the global space.
def f():
x = 'local'
print(x)
x = 'global'
f()
print(x)
def f():
x = 'local'
print(x)
x = 'global'
f()
print(x)
local
global
def f():
x = 'local'
print(x)
x = 'global'
f()
print(x)
local
global
Line 1: x in the global scope. Line 4: x in the local scope.
When f() is called, the local namespace of f() is active, therefore x = "local".
After f() terminates, the local namespace of f() terminates too. Therefore, back in the main program, x = "global".
def f():
print(x)
f()
def f():
print(x)
f()
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<stdin>", line 2, in f
print(x)
NameError: name 'x' is not defined
def f():
print(x)
f()
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<stdin>", line 2, in f
print(x)
NameError: name 'x' is not defined
x isn't defined at all.
The print() statement generates a NameError exception.