All variables declared inside a function is local to that function.
Python global , local and nonlocal variables declaration in functions and scope of the variables
n=5 # global
def my_fun():
n=6 # local variable
print("Inside function : ", n)
my_fun()
print("Out side function :",n )
Output
Inside function : 6
Out side function : 5
Value of global variable will not change outside the function.
n=5
def my_fun():
n=10 # local variable
n=n+1
print("Inside function : ", n )
my_fun()
print("Outside function:",n) # print value of global variable n
Output ( No change in value of n in 2nd print command outside the function. )
Inside function : 11
Outside function: 5
Using global we can use global scope variable inside function.
n=5
def my_fun():
global n
n= n+1
print("Inside function : ", n)
my_fun()
n= n+1
print("Outside function :", n)
Output
Inside function : 6
Outside function : 7
We can change the value of global scope variable inside the function and same will also reflect outside the function.
n=5
def my_fun():
global n
n= n+1
print("Inside function : ", n)
my_fun() # 6
n= n+1
print("Outside function (first ): ",n) # 7
my_fun() # 8
n=n+1
print("Outside function (second): ",n) # 9
Output
Inside function : 6
Outside function (first ): 7
Inside function : 8
Outside function (second): 9
nonlocal
In nested functions we can declare a variable as nonlocal to say that it is not a local variable.
Watch the difference in output of below two codes. In the second one we declared the variable as nonlocal so the value when we print at Outside value we get the value with the changes done inside the inner function my_fun2() ( n value as 20 )
Watch this code, when we remove the line saying a=2 , there is no error. If this line is kept then the error message says .
UnboundLocalError: local variable 'a' referenced before assignment
When you are assigning value to variable a , at that point the scope became local. Now compiler removes if any similar name variable is available in outer scope ( within that function ) and it mark it as local . So any accessing the variable before it is assigned will result error. So the print statement above ( with the line a =2 ) will create error as the local variable is not initialized before using.
However if you are not initializing the variable then it is not a local variable so no error.
Example accessing variables from outer scope
a=1
def my_function(x):
print("a: ",a) # accessing variables in outer scope, output 1
b=a+2 #accessing variable a in outer scope ( Not initializing )
print("b: ",b) # printing b as local variable output 3
return x+3
b=my_function(x=1)
print(b) # b from outer scope , output 4