What is global Keyword in Python?

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
Search for a command to run...

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
No comments yet. Be the first to comment.
When you’re building an application, one thing you can’t skip is API testing. Whether it’s a login flow, payment gateway, or a complex e-commerce workflow, ensuring your APIs behave correctly saves you from nasty surprises in production. I had alread...

PyPy is an implementation of Python written in RPython (Reduced Python) language, and it is seen as a replacement for CPython. PyPy claims that it is almost a drop-in replacement for CPython and can beat it on speed and memory usage. It supports libr...

You must have used functions provided by the os module in Python several times in your projects. These could be used to create a file, walk down a directory, get info on the current directory, perform path operations, and more. In this article, we’ll...

FastAPI is a fast and modern web framework known for its support for asynchronous REST API and ease of use. In this article, we’ll see how to stream videos on frontend in FastAPI. StreamingResponse Stream Local Video FastAPI provides a StreamingRespo...

Have you ever come across circular imports in Python? Well, it’s a very common code smell that indicates something’s wrong with the design or structure. Circular Import Example How does circular import occur? This import error usually occurs when two...
In Python, variables can be declared in two main scopes: global and local. Global variables are accessible from anywhere in the code, while local variables are only accessible within the function or block where they are defined.
Python has the "global" keyword, which allows users to modify global variables from within the local scope.
Let's understand with an example.
# Example of "global" keyword
# Global variable
var = "declared as global"
def modify_var():
# Function's scope
global var
# Modified the global variable "var"
var = "modified global"
print(var)
modify_var()
print(var)
In this example, the global variable var is defined first, followed by the function modify_var().
Inside the modify_var() function, the global var statement is used to reference the global variable var in the function's scope and then the variable var is modified and printed.
The function is then called. Upon running the code, you'll get the following result.
modified global
modified global
You can observe that the global variable var is modified.
In conclusion, the global keyword is used to reference and modify a global variable within the scope of a function.
What happens if you do not use the global keyword and attempt to modify a global variable within the local scope?
# Global variable
var = "declared as global"
def modify_var():
# Function's scope
# Trying to modify the global variable "var"
var = "modified global"
print(var)
modify_var()
print(var)
In this example, the global var statement is removed from the function and an attempt is made to modify the variable var.
modified global
declared as global
You can observe that the global variable var remains unchanged.
The global keyword can also be used to create a global variable in the local context.
def separate():
text = "Geek Python"
print(text.split(" "))
separate()
print(text)
In this example, the text variable is declared within the separate() function and has scope within the function only.
The text variable is being accessed outside of the function scope. This will result in an error.
['Geek', 'Python']
Traceback (most recent call last):
...
print(text)
^^^^
NameError: name 'text' is not defined. Did you mean: 'next'?
When you add a global statement just above the text variable, it becomes the global variable, which may be accessed from anywhere in the code.
def separate():
global text # Added global stmt
text = "Geek Python"
print(text.split(" "))
separate()
print(text)
When you run the code, you'll get the value stored in the text variable.
Consider the following example which attempts to change the global variable within the local scope without using the global statement.
# Global variable
initial = 2
def increment():
for x in range(10):
# Assigning value to the global var in local context
initial += x
increment()
print(initial)
A global variable named initial is declared and initialized with the value 2.
The function named increment() increments the global variable initial. The function is then called and the value of the initial variable is printed.
When you run the code, you'll get the following result.
Traceback (most recent call last):
...
increment()
...
initial += x
^^^^^^^
UnboundLocalError: cannot access local variable 'initial' where it is not associated with a value
The error message indicates that the local variable "initial" cannot be accessed. Python interprets the function's initial variable as a new local variable, which is why the code failed to locate the initial variable within the function's scope and returned an error.
However, when you add a global statement (global initial) within the function, Python will know that it is now referencing the existing global variable within the local scope.
# Global variable
initial = 2
def increment():
global initial
for x in range(10):
# Assigning value to the global var in local context
initial += x
increment()
print(initial)
You won't get an error when you run the code as the global statement has been added to the function scope.
47
The global keyword can be used to reference and modify an existing global variable within a local scope. If the global variable does not already exist, the global keyword can be used to create it within the local scope of a function.
🏆Other articles you might be interested in if you liked this one
âś…Yield Keyword in Python with Examples?
âś…Best Practices: Positional and Keyword Arguments in Python
âś…Python's __getitem__ method?
âś…Create a WebSocket Server and Client in Python.
âś…Create and Interact with MySQL Database in Python
âś…Understanding the Different Uses of the Asterisk(*) in Python?
That's all for now
Keep Coding✌✌