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
n=5
def my_fun1():
n=10
def my_fun2():
n=20
print("Inside n:",n) # 20
my_fun2()
print("Outside n :",n) # 10
my_fun1()
print("Main n :",n) # 5
Output
Inside n: 20
Outside n : 10
Main n : 5
With nonlocal
n=5
def my_fun1():
n=10
def my_fun2():
nonlocal n
n=20
print("Inside n:",n) # 20
my_fun2()
print("Outside n :",n) # 20
my_fun1()
print("Main n :",n) # 5
Output
Inside n: 20
Outside n : 20
Main n : 5
a=1
def my_function(x):
print("a: ",a)
#a = 2
return x
b=my_function(x=1)
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 . 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
Functions
All Built in Functions in Python
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.