Global Variables in Python

Previous
Next

Global variables:

  • Defining a variable outside to all the functions.
  • We can access the variable directly.
  • It is available throughout the application.
a=10 #global
def m1():
    print("Inside m1 :",a)
    return

def m2():
    print("Inside m2 :",a)
    return

m1()
m2()
print("Outside :",a)
  • We can define local & global variables with the same name.
  • We access both the variables directly using its identity.
  • When we access a variable inside the function, it gives the first priority to local variable.
  • If local is not present, then it is looking for Global variable.
a=10 #global
def m1():
    a=20 #local
    print("Inside m1 :",a)
    return

def m2():
    print("Inside m2 :",a)
    return

m1()
m2()
print("Outside :",a)
  • Python is interpreted, hence the instructions execute one by one sequentially.
  • We cannot access a variable before definition(memory allocation)
a=10
print("a :",a)
b=20
print("b :",b)
print("c :",c) # error : not yet defined
c=30

Global variable can be declared anywhere in the program but outside to all the functions

def m1():
    print("a value :",a)
    return

def m2():
    print("b value :",b)
    return

a=10 #global
b=20 #global

m1()
m2()
  • We cannot access a function before its definition
  • Python is interpreted
test() #Error : not yet defined

def test():
    print("func..")
    return

test() #allow

Check the output:

def m1():
    print("a value :",a)
    return

def m2():
    print("b value :",b)
    return

a=10 #global
m1()
m2()
b=20 #global
  • We can access global variable inside the function
  • We cannot modify the global variable from function directly.
a=10

def test():
    print("a val :",a)
    a=a+20 #error :
    print("a val :",a)
    return

test()
Previous
Next

Add Comment

Courses Enquiry Form