Use of Global Keyword In Python Programming

In this Python tutorial, I will teach you about what is the global keyword, variable and when to use them in Python programming language.

For a better understanding, I suggest you read my previous article where I discussed the use of Global variables in Python programming in detail.

In this tutorial, you will learn the following important things.

What Is Global Keyword In Python Programming?

In Python Global keyword is used to modify the variable outside of its scope. Variables have different scopes according to their accessibility.

A Global variable can be accessed from outside of a function.

In some cases, we need to change a variable that is present inside of the function body but from the outside of its current scope. In such cases, the Global keyword is used.

Rules Of Global Keyword

There are some rules that need to follow if you want to declare a Global variable in Python programming.

  • A variable that is defined outside of a function is global by default.
  • Inside of a function we use global keyword to read and write the instructions.
  • A variable declared outside of a function has no effect. There is no need to use global a keyword with it.
  • The variable that is declared inside of a function declared as local implicitly.
  • There is no need to use global a keyword with a variable that is defined outside of a function.

Practical Examples Of Global Keyword

Below are some useful examples for explaining the working of the Global keyword in Python programming.

Example 1: Accessing global Variable From Inside a Function

x = 5 # it is a global variable

def addition():
    print(x)

addition()

Output:

5

Example 2: How to Accessing global Variable From Inside a Function

# A Python program to you that there is no need to 
# use global keyword for accessing a global value 
  
# These are global variables 
x = 10
y = 10
  
# function to perform addition 
def addition(): 
    z = x + x 
    print(z) 
  
# it is a function call 
addition() 

Output:

20

In some cases, we want to change the global variable from inside a function. Let’s have look at the below examples.

x = 5 # it is global variable
    
def addition():
    x = x + 5 # increment x by 2
    print(x)

addition()

Output:

x = x + 5 # increment x by 2                                                                                              
UnboundLocalError: local variable 'x' referenced before assignment

We got an error here.

The reason is that a global variable can only be accessed but it is not allowed to modify it from inside the function.

The Solution is really simple. We need to use the global keyword in order to change the value from inside the function.

x = 0 # it is a global variable

def addition():
    global x
    x = x + 6 # increment by 6
    print("Inside addition():", x)

addition()
print("The result of addition is:", x)

Output:

Inside addition(): 6                                                                                                          
The addition is: 6

You can see you have no error this time.

In the above example, we declare a variable “x” as a global variable and use it inside the addition() function.

After declaration, we increment the variable “x” by 1 then we call the addition() function and print the global variable “x”

Use of Global Keyword Across Different Python ModulesĀ 

The best programming practice using a global keyword across different modules in the same program is to create a module generally named as config or cfg.

For doing this you have to import this module for your program or application only then the module will work as a global keyword.

You have only one instance of each module so keep in mind any changes you made to the module it gets reflected everywhere.

We understand this by the following example.

Example of Using Global Keyword with Python Modules

In this example, we simply create a file name config.pyto save the global keyword.

import config  #import config module
config.a = 1
config.b = 2
config.c ="WalkIntoPC"

Now we create a file named as modify.py in order to modify the global keyword

a = 0
b = 0
c ="none"

The above example shows the values of a, b, and z have been modified. Now to access these variables we have to import the config module.

To gain access to these variables we can do this by using config.variable_name to access these variables.

We have to create a main.py file to modify global keywords.

import config 
import modify 
print(config.a) 
print(config.b) 
print(config.c)

Output:

1
2
WalkIntoPC

This module config.pyis used to store the global variable a and b. After that, we create a modify.pyto modify the values of a and b.

In the same way, in main.pyfile we import both config.py and modify.py at the same time. In the end, we just print the values stored in the global variable.

Global Variable in Nested Functions

Nested function means a function with other functions within its body. Now you will learn how to use a global variable inside a nested function.

def foo():
    a = 25

    def borrow():
        global a
        a = 30
    
    print("Before calling borrow: ", a)
    print("Calling borrow now")
    borrow()
    print("After calling borrow: ", a)

foo()
print("a in main : ", a)

Output:

After calling borrow:  20                                                                                                     
a in main :  25

In the above code, “a” global variable is mentioned inside a nested function borrow().You can see we have a function foo()also.

But “a” has no effect on the global variable inside the borrow() function.

At first variable “a” stores the value of local variable a = 25. On the other hand, outside of the foo()function, variable a stores the value defined inside the borrow()function like a = 30.

The reason for is because we use a global keyword in “a” to declare a global variable inside the borrow()function.

I hope after this detailed and thorough article you can better understand what is global keywords? How we can use them and what are their scopes in Python programming language.

I am sure that after this article you will be able to apply this knowledge in any of your projects without having any trouble.

Maybe you would like to read about Variables, Data Types and Type Conversion in Python.

In case we have made any changes insdie the borrow()function, the changes reflects outside the local scope as in foo()function.

Jack Sparrow

Hay I Am Admin Of This Website. I Am Very Passionate About Computers And Technology. This Website Is The Result Of My Passion. I Love To Eliminate The Barriers That Come In Seeking Education. This Website Is The Free Source Of Learning About New Technology And Up To Date Knowledge.

This Post Has 2 Comments

  1. Jameel Bagh

    Python is necessary today or not ?

    1. Jack Sparrow

      Python is a very popular multi-purpose object-oriented language used in the world’s top organizations like Google, NASA, NetFlix, etc. So if you are serious about programming then Python is the best choice.

Leave a Reply