What are the rules for a local and global variable in Python ?

  • In python local variables are those which are defined inside a function and its scope is limited to that function only whereas global variables are those which are not defined inside any function and have a global scope.
  • We can say that global variables are accessible throughout the program and inside every function whereas local variables are accessible only inside the function in which it was initialized.

Local Variables

  • Inside function local variables are those which are initialized and belongs only to that particular function.
  • Then it cannot be accessed anywhere outside the function.

Sample Code

def f():
     
    # local variable
    s = "I love Wikitechy"
    print(s)
 
# Driver code
f()

Output

Global Variables

  • Outside any function the global variables are those which are defined and which are accessible throughout the program.

Sample Code

# This function uses global variable s
def f():
    print("Inside Function", s)
 
# Global scope
s = "I love Wikitechy"
f()
print("Outside Function", s)

Output

Leave a Reply

Your email address will not be published.

You May Also Like