Python : How to use global variables in a function ?

In this article we will discuss difference between local & global variable and will also see ways to access / modify both same name
global & local variable inside a function.


Table of Contents

Local variable vs Global variable

Local variable is a variable that is defined in a function and global variable is a variable that is defined outside any function or class i.e. in
global space. Global variable is accessible in any function and local variable has scope only in the function it is defined. For example,

# Global variable
total = 100

def test():
    # Local variable
    marks = 19
    print('Marks = ', marks)
    print('Total = ', total)

Here 'total' is a global variable therefore accessible inside function test() too and 'marks' is a local variable i.e. local to function test() only. But what if we have a scenario in which both global & local variables has same name ?

Global & local variables with same name

Checkout this example,

total = 100 

def func1(): 
   total = 15 

print('Total = ', total) 

func1() 

print('Total = ', total)
Output:
Total = 100 
Total = 100

Here 'total' is a global variable and func() function has a local variable with same name. By default a function gives preference to
local variable over global variable if both are of same name. Therefore in above code when we modified 'total' variable inside the function then it was not reflected outside the function. Because inside function func() total variable is treated as local variable.

But what if want to access global variable inside a function that has local variable with same name ?

Use of “global†keyword to modify global variable inside a function

If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.

global total

It will make the function to refer global variable total whenever accessed. Checkout this example,

total = 100
def func():
    # refer to global variable 'total' inside function
    global total
    if total > 10:
        total = 15

print('Total = ', total)
func()
print('Total = ', total)

Output:

Total =  100
Total =  15

As you can see modification done to global variable total is now visible outside the function too.

When we use global keyword with a variable inside the function then the local variable will be hidden. But what if we want to keep bot the local & global variable with same and modify both in the function ? Let's see how to do that,

Using globals() to access global variables inside the function

As 'global' keywords hide the local variable with same name, so to access both the local & global variable inside a function there is an another way i.e. global() function.
globals() returns a dictionary of elements in current module and we can use it to access / modify the global variable without using 'global' keyword i,e.

total = 100

def func3():
    listOfGlobals = globals()
    listOfGlobals['total'] = 15
    total = 22
    print('Local Total = ', total)

print('Total = ', total)
func3()
print('Total = ', total)

Output:

Total =  15
Local Total =  22
Total =  11

As you can see that we have local variable and global variable with same name i.e. total and we modified both inside the function. By using dictionary returned by globals() to refer global variable instead of keyword 'global'. It will not hide local variable inside the function.

Handling UnboundLocalError Error

If we try to access a global variable with 'global' keyword or globals() inside a function i.e.

total = 22
def func2():
    if total > 10:
        total = 15

It will throw an error like this,

UnboundLocalError: local variable 'total' referenced before assignment

To prevent this error we either need to use 'global' keyword or global() function i.e.

total = 22 

def func2():
    global total
    if total > 10:
        total = 15

The Complete example of global variable and globals() in Python

# Global variable
total = 100

def test():
    # Local variable
    marks = 19
    print('Marks = ', marks)
    print('Total = ', total)

def func1():
    total = 15

def func():
    # refer to global variable 'total' inside function
    global total
    if total > 10:
        total = 15

def func2():
    global total
    if total > 10:
        total = 15

def func3():
    listOfGlobals = globals()
    listOfGlobals['total'] = 11
    total = 22
    print('Local Total = ', total)


def main():
    print('Total = ', total)
    func1()
    print('Total = ', total)
    func()
    print('Total = ', total)
    func2()
    print('Total = ', total)
    func3()
    print('Total = ', total)

if __name__ == '__main__':
    main()

Output:

Total =  100
Total =  100
Total =  15
Total =  15
Local Total =  22
Total =  11

1 thought on “Python : How to use global variables in a function ?”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top