Global Local and Nonlocal variables

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 )
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
Functions All Built in Functions in Python

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer