global
vs nonlocal
statements¶
Defining a global variable:¶
In [1]:
def make_global():
global x
x = 10
make_global()
print(x)
We can also define a global
variable inside of a function which could also be accessed from another function:¶
In [2]:
def func():
global k
k = 12
def other_func():
print(k)
func()
other_func()
If I tried to do that without global
I get an error:¶
In [3]:
def func():
z = 12
func()
print(z)
In [4]:
a_variable = 10 # inherently global
def func():
print(a_variable)
func()
In [5]:
def func():
fruit = 'apple'
def func_inner():
fruit = 'orange'
func_inner() # Calling the inner function
return fruit # This is what is getting printed
print(func()) # apple
As you can see func() returned apple. Setting it to 'orange' inside of the inner function did nothing to the original fruit. Only the inner function knew it was orange for the duration of that inner function.¶
Here is the same functions with the nonlocal statement¶
In [6]:
def func():
fruit = 'banana'
def func_inner():
nonlocal fruit
fruit = 'pear'
func_inner()
return fruit
print(func()) # pear
You can see that the fruit was changed to 'pear' and 'banana' was overwritten.¶
Now if I had a global fruit 'cherry' would it be overwritten?¶
In [7]:
fruit = 'cherry'
def func():
fruit = 'raspberry'
def func_inner():
nonlocal fruit
fruit = 'apricot'
func_inner()
return fruit
print(func()) # changed to apricot
print(fruit) # stays the same
In [8]:
fruit = 'nectarine' # changes THERE
def func():
fruit = 'tomato' # does not change
def func_inner():
global fruit
fruit = 'avocado' # changes HERE
func_inner()
return fruit # still tomato
print(func()) # tomato
print(fruit) # avacado