Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
What is the global keyword in Python?
3.
What is the purpose of global keywords in python?
3.1.
Python
4.
Rules of Global Keyword in Python
5.
Use of Global Keyword
6.
Global Scope in Python
6.1.
Python
7.
Example of Global Keyword in Python
7.1.
Example 1: Changing global Variable From Inside a Function
7.2.
Python
8.
Global Variables Across Python Modules
8.1.
Create a config.py file to store the global variables
8.2.
Create a update.py file to update the global variables
8.3.
Create a main.py file to print the changed value of global variables
9.
Global Variables in Nested Functions 
9.1.
Python
10.
Frequently Asked Questions
10.1.
What is global keyword in Python?
10.2.
What is the use of globals ()?
10.3.
What is globals() in Python?
10.4.
What is global reference in Python?
10.5.
What is global module in Python?
11.
Conclusion
Last Updated: Mar 27, 2024
Medium

Global Keyword in Python

Author Shiva
0 upvote
gp-icon
Basics of python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction 

When coding in Python, you may encounter situations where you need to restrict the accessibility of a variable to a specific code block. This is achieved by limiting the variable's scope. Python offers two types of scopes: Local Scope and Global Scope, each determining where variables are visible and accessible. This is where Global keyword comes into the picture.

In this blog, we will be covering the concept of Global keyword in Python, along with some examples.

Global keyword in python

What is the global keyword in Python?

In Python, the global keyword is used to declare that a variable inside a function should refer to the global variable of the same name, rather than creating a new local variable. This allows modifying the value of a global variable from within a function.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is the purpose of global keywords in python?

In Python, the global keyword is used to declare that a variable inside a function is referring to a global variable defined outside the function rather than creating a new variable with the same name as the global variable inside the function. This allows the function to modify the value of the global variable instead of creating a new local variable with the same name. The global keyword is used to access and modify global variables from within a function, and it is especially useful when working with larger programs or modules.

Must Read, Divmod in Python

In Python, the global keyword is used to modify the variable outside of the current scope.  The global keyword is used inside a function when the variable has to be updated using the variable’s initial value. However, it is not required to print or access the variables in the function.

Let’s see what happens when we try to update a global variable inside the function by using the variable’s initial value.

# global scope
name = "Coding"
def func():
name = name + " Ninjas"
print(name)   
func()

 Error:

An error is obtained as Python treats “name” as a local variable, and we have not defined any local variable “name” inside the func(). To solve this error, we use the global keyword.
 

  • Python

Python

# global scope
name = "Coding"
def func():
#global keyword used
global name
# name updated
name = name + " Ninjas"
print("Inside function: " + name)  
func()
print("Outside function: " + name)

Output

Inside function: Coding Ninjas
Outside function: Coding Ninjas

Notice that the change has also occurred on the global variable outside the function.

Also see, Merge Sort Python

Rules of Global Keyword in Python

The basic rules for the global keyword in Python are:

  • A variable created inside a function is local by default unless explicitly declared global
     
  • A variable declared outside of a function is global by default
     
  • The global keyword is used to make a variable global inside a function
     
  • The use of the global keyword outside of a function is unnecessary

Use of Global Keyword

In Python, the global keyword is used to indicate that a variable declared inside a function should be treated as a global variable, rather than a local variable. This means that the variable can be accessed and modified both inside and outside the function. Let us see what we can do without and with global keyword:

  • Without the global keyword: If we define a variable inside a function without using the global keyword, it is treated as a local variable. This means that the variable is only accessible within that function, and any modifications to it won't affect the variable with the same name outside the function
     
  • With the global keyword: When we use the global keyword before declaring a variable inside a function, it tells Python that the variable should be treated as a global variable. This means that the variable can be accessed and modified from both inside and outside the function, affecting the same variable in the global scope

Global Scope in Python

In Python, a variable declared outside the function is said to have a global scope. The variable can now be accessed both inside and outside of the function. The variable with global scope is called the global variable.

A variable declared in the top-level segment of the python program is said to have a global scope and can be used anywhere in the program. Let’s now look at an example to understand the global scope.

  • Python

Python

# global scope
name = "Coding Ninjas"
def func():
print(name)
func()

Output

"Coding Ninjas"

Example of Global Keyword in Python

Example 1: Changing global Variable From Inside a Function

It is possible to change the value of a global variable from inside a function in Python by using the global keyword to indicate that the variable should be treated as a global variable, like this:
 

  • Python

Python

x = 1
def change_global():
global x
x = 2
change_global()
print(x)

Output

"2"

However, it is generally considered better programming practice to avoid relying on global variables and instead pass values between functions using function arguments and return values.

Global Variables Across Python Modules

In Python, a file containing the Python statements and definitions is called a module. To share global variables across different modules within the same program, we create a single module (often named config.py). This module holds the global variables and shares the information across Python modules within the same program.

We import the config module in all the required modules to share global variables across different modules within the same program. This module now becomes available as a global name. Only one instance of each module is present, so any changes made to the module object are reflected everywhere.

Let’s see an example to understand how global variables are shared across the python modules.

Create a config.py file to store the global variables

# global variables of name and year stored
name = "Coding"
year = 2020

Create a update.py file to update the global variables

# import config module
import config
# modify the global variables
config.name = "Coding Ninjas"
config.year = 2021

Create a main.py file to print the changed value of global variables

# import both config and update module
import config
import update
# print the updated value
print("Modified value of name: " + config.name)
print("Modified value of year: ", config.year)

Output

Modified value of name: Coding Ninjas
Modified value of year: 2021

You can practice by yourself with the help of online python compiler.

Global Variables in Nested Functions 

To use global inside a nested function, we must declare a variable with a global keyword inside a nested function. Here is how global variables are used in a nested function.

  • Python

Python

year = 2020

def func():
def change():
global year
year = 2021

# Local variable year printed
print("Before changing local variable year:", year)
change()
# Local variable year printed
print("After changing local variable year:", year)

# Global variable year printed
print("Global variable year:", year)

func()

Output

Before changing local variable year:  2020
After changing local variable year:  2020
Global variable year:  2021

 

In the above program, a global variable is declared inside the nested function change().

Inside func(), “year” has no effect on the global keyword. Before and after calling change(), the variable “year” takes the value of the local variable, i.e., 2020. 

Outside of func(), the variable year will take value defined in change()  i.e 2021. This is because the global keyword has been used in “year” to create a global variable inside the change().

If any changes have been made inside the change(), the changes appear outside the local scope, i.e., func().

Also check out Python Square Root here.

Frequently Asked Questions

What is global keyword in Python?

In Python, the global keyword indicates that a variable declared inside a function should be treated as a global variable rather than a local variable. This allows the variable to be accessed and modified from outside the function.

What is the use of globals ()?

In Python, the globals() function is used to return a dictionary containing all the global variables in the current scope. This can be useful for inspecting or modifying global variables at runtime.

What is globals() in Python?

globals() is a built-in function in Python that returns a dictionary representing the global symbol table. It contains all global variables and their corresponding values accessible from the current scope.

What is global reference in Python?

In Python, a global reference refers to accessing a variable defined in the global scope from within a function or other nested scopes, using the global keyword to modify its value if necessary.

What is global module in Python?

The term may refer to accessing global variables or modules from any part of the program, indicating their accessibility throughout the codebase.

Conclusion

That was all about the global keyword in Python. In this blog, we covered the concept of local scope, global scope, rules of the global keyboard in Python, accessing the global variables across Python files, and some FAQs related to the global keyboard in Python.

Recommended Readings:

Do check out The Interview guide for Product Based Companies as well as some of the Popular interview problems from top tech companies like Amazon, Adobe, Google, Uber, Microsoft, etc.

Refer to our guided paths on Coding Ninjas Studio to learn more about Competitive ProgrammingJavaScriptSystem Design, etc. Enroll in our courses and refer to the mock test and problems available; take a look at the interview experiences and interview bundle for placement preparations.

Previous article
*Args and **Kwargs in Python
Next article
range vs xrange in Python
Guided path
Free
gridgp-icon
Basics of python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass