Methods and Functions

Python Global Keyword (With Examples)

Many a time we are required to declare a variable that is to be used for multiple times in our program. But its value can keep changing according to the situation and the function it is being used for. Hence, Python provides us a method to declare a variable globally, which can be accessed within class and functions, and the value of it can be changed only for that class or function respectively. Python global keyword is used to declare that variable in the program. This article will learn more about the Python global keyword, its syntax, when to use it, and examples for proper understanding.

What is the Global Keyword?

  • Python global keyword allows the user to define a variable globally whose value can be modified outside the current scope.

The term global denotes that the scope of a variable declared as global will persist for the duration of the entire program’s execution. We utilize the global keyword inside a function only when we wish to conduct value assignments or update a variable.

Rules of Global Keyword

Few basic rules for using the Python global keyword:

  • Without the use of the global keyword, a variable created inside any function is a Local variable by default.
  • Variable defined outside the function is Global by default. No need to use the global keyword.
  • Global keyword is used when we want to read or write any global variable value inside the function.
  • The global keyword used for a variable declared outside the function does not have any effect on it.
  • In the same line, a variable cannot be declared global and assigned a value. E.g. global x = 5 is not allowed.

Use of Global Keyword

In a Python program, distinct variables have different scopes. The variable may or may not be available inside a function, depending on where it is declared. We may need to change a variable inside a function from outside its current scope on occasion. In this case, we utilize the global keyword in conjunction with the variable name.

In Python, the global keyword allows you to change a variable value outside of its current scope. It is used to make changes to a global variable from a local location. The global keyword is only required for altering the variable value and not for publishing or accessing it.

Let us understand various examples where can we use the global keyword.

  1. Accessing Global variable from inside the function

In this example, the variable is declared outside the function i.e., globally. We will simply fetch the variable into the local function and print it.

Example 1 –

                    

# Python program to illustrate the usage of global variable in a local function
num = 25   # Global variable 
def display():
    print('Global Variable value inside function:', num)

display()

Output –

                    

Global Variable value inside function: 25

Example 2 –

                    

a = int(input('Enter 1st Value: '))   # Global variable
b = int(input('Enter 2nd Value: '))   # Global variable

def operation():
    c = a * b
    # Multiplication using 2 global variables in local function
    print('Multiplication Value:', c)

operation()

Output –

                    

Enter 1st Value: 5
Enter 2nd Value: 20
Multiplication Value: 100

  1. Updating/Modifying Global variable from inside the function

In this example, we try to update/change the global variable ‘roll_no’ from within the function. But the Python interpreter displays an error. This is because we can only access the global variable from within the function and not edit it.

Example –

                    

stud = 'Joshua' # Global variable
roll_no = 26    # Global variable

def display():
    roll_no = roll_no + 2
    # Updating 1 global variable in local function
    print('Correct Student roll_no:', roll_no)

display()

Output –

                    

Traceback (most recent call last):
File "", line 9, in 
File "", line 5, in display
UnboundLocalError: local variable 'roll_no' referenced before assignment

In order to solve this issue, Python provides a global keyword. Let us look at the usage of this keyword on the same example in the next part.

  1. Using the global keyword in local function to modify the global variable value

In the following example, we declared ‘roll_no’ as a global variable inside the local function. When we increment the value of the variable in the function, it does not give any error as compared to the previous example. Also, changing the value of the global variable inside the function display() has an effect on the value of the outside global variable too, as we can see in the below example.

Example –

                    

stud = 'Joshua' # Global variable
roll_no = 26    # Global variable

def display():
    global roll_no
    roll_no = roll_no + 4
    # Updating 1 global variable in local function
    print('Inside display() student roll_no value:', roll_no)

display()
print('Global variable roll_no value:', roll_no)

Output –

                    

Inside display() student roll_no value: 30
Global variable roll_no value: 30

Global variables across Python Modules

It is strongly recommended to develop a new module if there is a specific demand for a set of global variables that must be utilized in many distinct modules or programs. The global objects/variables will be contained in this module, which can be easily imported into the scripts that require or use them. The file can be called config.py. The application’s config file becomes a global module. Any modifications made in this config module will be reflected in any other modules that utilize it. This method is suggested since it keeps all of your global items in one place.

Let us understand more by looking at the following example for sharing a global variable across Python modules–

                    

# Create config.py file to store global variables separately
name = 'nil'
msg = 'empty'
mobile = 0

                    

# Create modify.py file to assign separate values to global variables
import config   # import config.py file global variables

config.name = 'Sean'
config.msg = 'Welcome Home!'
config.mobile = 9753276843

                    

# Create main.py file to test the value changes
import config
import modify

print(config.name)
print(config.msg)
print(config.mobile)

Output –

                    

Sean
Welcome Home
9753276843

In the above example, we have created 3 files config.py, modify.py, and main.py. The module config.py stores the global variables to be used. The 2nd file modify.py is used to import config.py file global variables and then assign new values to it. In the main.py file, we import both the above files and then print the values of global variables and check if they are updated or not.

Python Global in Nested functions

The global keyword can also be used with the Nesting method. We must define a variable with the global keyword inside a nested function in order to use global inside a nested function.

Example –

                    

# Python program to illustrate global keyword in nested functions
def func():
    val = 20   
    def change():
         global val
         val = 50
         print('Inside change():', val)       
    print('Inside func():', val)
    print('Calling change() nested function')
    change()
    print('After calling change():', val)

func()
print('Global variable value now:', val)

Output –

                    

Inside func(): 20
Calling change() nested function
Inside change(): 50
After calling change(): 20
Global variable value now: 50

In the above example, The variable ‘val‘ takes the value of the local variable before and after using change(), i.e. val = 20. The variable val will take the value defined in the change() function outside of the funct() method, i.e. val = 50. Because we used the global keyword for val to establish a global variable within the nested function change() (local scope).

Note – It’s crucial to note that using the global keyword should be avoided in most circumstances because it makes program logic encapsulation difficult.

Frequently Asked Questions

Q1. What is a global in Python?

In Python, every “variable” has a certain scope. Locally scoped objects and variables die when the function terminates and cannot be recovered. You use the global keyword to tell Python that a variable in your function is defined at the global (module-level) scope. In other words, if you use the python global keyword, you can modify the value of a global variable in the module scope from within a function.

The term global denotes that the scope of a variable declared as global will persist for the duration of the entire program’s execution. We utilize the global keyword inside a function only when we wish to conduct value assignments or update a variable.

Q2. How do you declare a global variable in Python?

Variables that are defined outside the function are by default global variables. Everyone can utilize Python global variables, both inside and outside of functions. If a Python global variable is defined inside the function, and if we want to change the value of it, then we need to first specify the global keyword and then concatenate the variable name. Only then we are able to modify the global variable in the local scope i.e. in the function.

Example –

                    

num = 5  # Global variable

def display():
    global num
    num = num * 4
    # Updating global variable in local function
    print('Inside display() num value:', num) 

display()
print('Global variable num value:', num)

Output –

                    

Inside display() num value: 20
Global variable num value: 20

Note – In the same line, a variable cannot be declared global and assigned a value. E.g. global x = 5 is not allowed.

Q3. Why is global bad in Python?

One of the major disadvantages of the global variables is that because they are accessible to all functions, it becomes progressively difficult to determine which functions actually read and write them. It becomes confusing to detect which local scope is using these global variables and where the value is being changed or updated.

Global variables are used 90% of the time to reduce the cost of transferring a parameter around. But then there arises multithreading, unit testing, and maintenance coding, and you’ve got an issue. In multi-threaded or multiprocessing contexts, the value of a variable can be altered by other code in the middle of a statement, causing issues.

Also, it is crucial to note that using the global keyword should be avoided in most circumstances because it makes program logic encapsulation difficult.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.