20% off on all our Foreign language and IT courses! Avail now!
What Is Global Variable in Python?
Python
April 3, 2025
Blog summary: What is Global variable in Python? Let’s define the data values accessible throughout the program. Let’s understand what a global variable is in Python and how to create and access it.
Python is a versatile and powerful programming language that enables developers to define and use variables across several contexts. Understanding variable scope, specifically global and local variables, is a key subject in Python programming.
In Python, variables are building blocks used to store, manage, and modify data. Thanks to Python’s easy-to-read syntax and dynamic typing, variables are easy to use within the code.
Though you don’t need to define the variable type in a code, there are significant differences between how global and local variables are used and accessed in Python.
Often, Python beginners struggle to understand what a global variable is in Python. How do you declare a global variable in Python? When should local and global variables be used in Python?
To help you out, we have drafted a detailed blog on global variables in Python. The blog explains how to use global variables in Python, best practices, and the difference between global and local variables in Python.
In Python, a global variable is defined outside any function or class and can be accessed from anywhere in the program. A global variable has scope throughout the program, which means that its value is available throughout the program unless concealed.
Global variables are essential for storing data that must be accessed and altered across many scopes or functions of a program. When you declare a variable as global, it becomes available to all functions and modules in your codebase.
Example-
name = “Alice”
def greet():
global name # Accessing the global variable
print(f”Hello, {name}!”)
greet() # Output: Hello, Alice!
Usage and Scope of Global Variable
A global variable is a variable declared outside of a function, making it accessible throughout the entire program. It can be read and modified inside functions using the global keyword.
Now, let’s discuss how to use the Global variable in Python.
Usage of Global Variable-
Storing Configuration Settings
Sharing Data Across Functions
Maintaining State in Programs
Scope of Global Variable-
Global Scope
Function Scope
Example of Global Variable Usage
count = 0
def increase ():
global count
count += 1
print(f”Count: {count}”)
increase () # Output: Count: 1
increase () # Output: Count: 2
What are the types of variables in Python?
Variables in Python store data in Python programming. In simple words, understand these as containers that store different types of data.
You don’t have to declare the type of data in the variable, as it is recognized by the value stored in it. So, to declare a variable in Python, you must use “=” and assign a value to it.
The variables in Python are divided into 5 categories based on their scope and data. Python has various data types, such as numerical, string, Boolean, tuple, list, set, dictionary, and NoneType.
The four types of variables in Python are:
Local variables
Global variables
Static variable in Python
Instance variables
Let’s understand these in detail.
What are global and local variables in Python?
In Python, a local variable is defined and called within a function. Its scope is limited to the Function in which it is accessed.
These are mainly used for storing data temporarily within a function and don’t affect the program.
Example:
def my_function():
y = 5 # Local variable
print(y)
my_function() # Output: 5
# print(y) # This would raise an error as y is not accessible outside the Function
Global variables declared outside of a function or class, offer unique flexibility. They can be accessed from anywhere within a program, inside or outside of a function. Their scope isn’t limited to the Function they’re declared but extends throughout the program, empowering developers with their versatility.
Developers use global variables when they need to apply data across multiple functions or classes.
Example:
x = 10 # Global variable
def print_x():
print(x) # Accessing global variable
print_x() # Output: 10
Now that you know what a global variable is in Python, let’s learn how to create it.
Difference between Global Variable and Local Variable in Python
Feature
Global Variable
Local Variable
Defined in
Outside a function
Inside a function
Scope
Accessible anywhere in the script
Accessible only within the function
Lifespan
Exists throughout the program
Exists only during function execution
Accessibility
Can be accessed from any function
Cannot be accessed outside its function
Modification
Needs global keyword to modify within a function
Directly modifiable within its function
How to create a global variable in Python?
To create a global variable in Python, you need to declare it outside the Function or within a worldwide scope. By scope, we mean the areas of the program that can access the variable. So, global scope means that the variable is accessible throughout the program.
Example of how to declare a global variable in Python:
# This Function uses global variable s
def f():
print(“Inside Function”, s)
# Global scope
s = “I love India my homeland”
f()
print(“Outside Function”, s)
The output you will get is as follows:
Inside Function I love India my homeland
Outside Function I love India my homeland
In the above example, you see how we accessed the global variable both inside and outside the Function.
How to access global variables in Python inside and outside of a function?
What is Global Variable in Python: Accessing a global variable in Python is straightforward. A global variable is available throughout the Python program, whether you want to access it within the Function or outside.
Accessing Python global variable outside a function
# Global variable
greeting = “Hello, World!”
# Accessing global variables outside of any function
print(greeting) # Output: Hello, World!
Accessing Python global variable inside a function
# Global variable
greeting = “Hello, World!”
def print_greeting():
# Accessing the global variable inside the Function
print(greeting) # Output: Hello, World!
# Call the Function
print_greeting()
How to use Global Keyword in Python
The global keyword in Python allows us to modify a global variable inside a function. Without global, Python treats the variable inside the function as a local variable. It instructs the interpreter to take up the global version of the variable value.
Example-
y = 10 # initializing a global variable
def add_five(): # defining a function
global y # using global keyword
y = y + 5 # changing the global variable
add_five() # calling the function
print(y) # accessing the global variable
Please note that once you use “global” before the variable, any changes made inside the Function will affect the global variable.
Also, overusing the “global” keyword in your code will make it hard to understand and debug. You should consider using return values and function arguments in your program.
What happens if global and local variables in Python have the same name?
Now, there are times when local and global variables have the same name.
In such cases, will the local variable affect the global variable? Or will the global variable overshadow the local variable in the program? How does Python prioritize both variables in the program?
What will happen if we change the value of the global variable in a function?
Python follows a set of rules to determine which variable to prioritize in a program based on its scope.
As discussed above, a variable scope is an area or part of the program that has access to the variable.
Global scope means the variable defined outside of a function. Variables can be called or accessed outside and inside of a function unless a local variable overrides them.
Local scope refers to the variables defined within the Function. These can be accessed only inside the Function and do not affect the global variable.
So, when we have a situation where both local and global variables have the same name:
Inside Function: Within the Function, a local variable is always given priority over the global variable. Any reference to the variable inside the Function will mean a local variable, not a global one.
Outside Function: Outside of the Function, a global variable is more vital than a local variable. This is because local variables cannot be accessed outside of a function. So, even if both local and global variables have the same name, any reference to variables outside the Function only refers to a global variable.
Example:
# Global variable
x = 10
def my_function():
# Local variable with the same name as the global variable
x = 5
print(“Value of x inside the function:”, x)
# Calling the Function
my_function() # Output: Value of x inside the function: 5
# Accessing the global variable outside the Function
print(“Value of x outside the function:”, x) # Output: Value of x outside the function: 10
As you can see in the above example, the variable called within the Function means variable “x” with value 5 and not the global variable with value 10.
So when “print(x)” is called within the Function, the code prints the value 5.
Moreover, when a variable is called outside the Function, the interpreter understands that the global variable “x” with value 10 is called. So, for “print(x)” outside of a function, the output is 10.
What happens if you try to change the value of a global variable inside the Function?
You will get an error as “UnboundLocalError.” Why?
Because you cannot modify the value of a global variable inside a function.
This is because Python interprets the variable inside the Function as a local variable. It is the nature of Python to take any variable inside the Function as local.
So, when you declare a variable “x” globally and try to modify it in a function, Python will treat “x” as local.
As you have not defined the variable “x” locally beforehand, Python does not know where to refer to and shows an error.
Example of the issue:
x = 10 # Global variable
def myfunc():
print(x) # Trying to access global x before modifying it
x = x + 5 # Attempt to modify x
print(x)
myfunc()
Python will not catch the global variable value for modifications within a function unless you use the “global” keyword.
Example of accessing and modifying global variables inside and outside a function:
# Global variable
total = 50
def add_to_total(amount):
global total # Declare that we are using the global variable
total += amount # Modify the global variable
def print_total():
# Accessing the global variable inside the Function
print(f”Total inside function: {total}”)
# Accessing the global variable outside the Function
print(f”Total before function call: {total}”) # Output: 50
# Modify the global variable inside the Function
add_to_total(30)
# Accessing the global variable outside the Function after modification
print(f”Total after function call: {total}”) # Output: 80
# Accessing the global variable inside another function
print_total() # Output: Total inside Function: 80
Best practices on how to use global variables in Python
Handling global variables in Python is easy if you follow the rules. Here are some best practices to use Python global variables.
Use descriptive names for global variables. The name should tell the purpose or nature of the value.
Use the “global” keyword only where necessary to modify the value of global variables in the Function.
Refrain from carelessly using the “global” keyword in your code. This makes your code hard to understand.
Minimize the use of global variables in your code. Go for alternatives like classes, return values, and function attributes.
Always clarify the purpose and intent when using the global variables. Use single-line comments to document why they are being used.
Remember to test your code rigorously when using global variables. This is to ensure that there are no side effects and that no part of the program is affected by them.
Global variables are best suited for simple applications and scripts. If your program grows, consider refactoring the code to eliminate them. This will make your code robust and scalable.
Variables in Python are essential elements that, when judiciously used, can help you write clear and bug-free code. Global variables are powerful tools in Python that should be used with caution. By naming them clearly, minimizing their use, and correctly documenting and thoroughly testing your code, you can handle global variables while keeping your code clean and maintainable.
Learn Python with Kochiva and get ready for a career in tech. Our expert trainers will teach you everything you need to know in the field of IT, and help you find a job.
Blog summary: What is Global variable in Python? Let’s define the data values accessible throughout the program. Let’s understand what a global variable is in Python and how to create and access it.
Python is a versatile and powerful programming language that enables developers to define and use variables across several contexts. Understanding variable scope, specifically global and local variables, is a key subject in Python programming.
In Python, variables are building blocks used to store, manage, and modify data. Thanks to Python’s easy-to-read syntax and dynamic typing, variables are easy to use within the code.
Though you don’t need to define the variable type in a code, there are significant differences between how global and local variables are used and accessed in Python.
Often, Python beginners struggle to understand what a global variable is in Python. How do you declare a global variable in Python? When should local and global variables be used in Python?
To help you out, we have drafted a detailed blog on global variables in Python. The blog explains how to use global variables in Python, best practices, and the difference between global and local variables in Python.
Let’s get started.
Read more: Online Python Course
Experience Live Classes
What is a Global Variable in Python?
In Python, a global variable is defined outside any function or class and can be accessed from anywhere in the program. A global variable has scope throughout the program, which means that its value is available throughout the program unless concealed.
Global variables are essential for storing data that must be accessed and altered across many scopes or functions of a program. When you declare a variable as global, it becomes available to all functions and modules in your codebase.
Example-
name = “Alice”
def greet():
global name # Accessing the global variable
print(f”Hello, {name}!”)
greet() # Output: Hello, Alice!
Usage and Scope of Global Variable
A global variable is a variable declared outside of a function, making it accessible throughout the entire program. It can be read and modified inside functions using the global keyword.
Now, let’s discuss how to use the Global variable in Python.
Usage of Global Variable-
Scope of Global Variable-
Example of Global Variable Usage
count = 0
def increase ():
global count
count += 1
print(f”Count: {count}”)
increase () # Output: Count: 1
increase () # Output: Count: 2
What are the types of variables in Python?
Variables in Python store data in Python programming. In simple words, understand these as containers that store different types of data.
You don’t have to declare the type of data in the variable, as it is recognized by the value stored in it. So, to declare a variable in Python, you must use “=” and assign a value to it.
The variables in Python are divided into 5 categories based on their scope and data. Python has various data types, such as numerical, string, Boolean, tuple, list, set, dictionary, and NoneType.
The four types of variables in Python are:
Let’s understand these in detail.
What are global and local variables in Python?
In Python, a local variable is defined and called within a function. Its scope is limited to the Function in which it is accessed.
These are mainly used for storing data temporarily within a function and don’t affect the program.
Example:
def my_function():
y = 5 # Local variable
print(y)
my_function() # Output: 5
# print(y) # This would raise an error as y is not accessible outside the Function
Global variables declared outside of a function or class, offer unique flexibility. They can be accessed from anywhere within a program, inside or outside of a function. Their scope isn’t limited to the Function they’re declared but extends throughout the program, empowering developers with their versatility.
Developers use global variables when they need to apply data across multiple functions or classes.
Example:
x = 10 # Global variable
def print_x():
print(x) # Accessing global variable
print_x() # Output: 10
Now that you know what a global variable is in Python, let’s learn how to create it.
Similar Blog: Advantages Of Python Over Other Programming Languages
Difference between Global Variable and Local Variable in Python
How to create a global variable in Python?
To create a global variable in Python, you need to declare it outside the Function or within a worldwide scope. By scope, we mean the areas of the program that can access the variable. So, global scope means that the variable is accessible throughout the program.
Example of how to declare a global variable in Python:
# This Function uses global variable s
def f():
print(“Inside Function”, s)
# Global scope
s = “I love India my homeland”
f()
print(“Outside Function”, s)
The output you will get is as follows:
In the above example, you see how we accessed the global variable both inside and outside the Function.
Informative blog: What is Multi Line Comment Line in Python?
How to access global variables in Python inside and outside of a function?
What is Global Variable in Python: Accessing a global variable in Python is straightforward. A global variable is available throughout the Python program, whether you want to access it within the Function or outside.
Accessing Python global variable outside a function
# Global variable
greeting = “Hello, World!”
# Accessing global variables outside of any function
print(greeting) # Output: Hello, World!
Accessing Python global variable inside a function
# Global variable
greeting = “Hello, World!”
def print_greeting():
# Accessing the global variable inside the Function
print(greeting) # Output: Hello, World!
# Call the Function
print_greeting()
How to use Global Keyword in Python
The global keyword in Python allows us to modify a global variable inside a function. Without global, Python treats the variable inside the function as a local variable. It instructs the interpreter to take up the global version of the variable value.
Example-
y = 10 # initializing a global variable
def add_five(): # defining a function
global y # using global keyword
y = y + 5 # changing the global variable
add_five() # calling the function
print(y) # accessing the global variable
Please note that once you use “global” before the variable, any changes made inside the Function will affect the global variable.
Also, overusing the “global” keyword in your code will make it hard to understand and debug. You should consider using return values and function arguments in your program.
What happens if global and local variables in Python have the same name?
Now, there are times when local and global variables have the same name.
In such cases, will the local variable affect the global variable? Or will the global variable overshadow the local variable in the program? How does Python prioritize both variables in the program?
Related Article: Top 10 Python Frameworks List
What will happen if we change the value of the global variable in a function?
Python follows a set of rules to determine which variable to prioritize in a program based on its scope.
As discussed above, a variable scope is an area or part of the program that has access to the variable.
Global scope means the variable defined outside of a function. Variables can be called or accessed outside and inside of a function unless a local variable overrides them.
Local scope refers to the variables defined within the Function. These can be accessed only inside the Function and do not affect the global variable.
So, when we have a situation where both local and global variables have the same name:
Inside Function: Within the Function, a local variable is always given priority over the global variable. Any reference to the variable inside the Function will mean a local variable, not a global one.
Outside Function: Outside of the Function, a global variable is more vital than a local variable. This is because local variables cannot be accessed outside of a function. So, even if both local and global variables have the same name, any reference to variables outside the Function only refers to a global variable.
Example:
# Global variable
x = 10
def my_function():
# Local variable with the same name as the global variable
x = 5
print(“Value of x inside the function:”, x)
# Calling the Function
my_function() # Output: Value of x inside the function: 5
# Accessing the global variable outside the Function
print(“Value of x outside the function:”, x) # Output: Value of x outside the function: 10
As you can see in the above example, the variable called within the Function means variable “x” with value 5 and not the global variable with value 10.
So when “print(x)” is called within the Function, the code prints the value 5.
Moreover, when a variable is called outside the Function, the interpreter understands that the global variable “x” with value 10 is called. So, for “print(x)” outside of a function, the output is 10.
Informative blog: Top 10 Web Development Frameworks to Use in 2024
What happens if you try to change the value of a global variable inside the Function?
You will get an error as “UnboundLocalError.” Why?
Because you cannot modify the value of a global variable inside a function.
This is because Python interprets the variable inside the Function as a local variable. It is the nature of Python to take any variable inside the Function as local.
So, when you declare a variable “x” globally and try to modify it in a function, Python will treat “x” as local.
As you have not defined the variable “x” locally beforehand, Python does not know where to refer to and shows an error.
Example of the issue:
x = 10 # Global variable
def myfunc():
print(x) # Trying to access global x before modifying it
x = x + 5 # Attempt to modify x
print(x)
myfunc()
Python will not catch the global variable value for modifications within a function unless you use the “global” keyword.
Example of accessing and modifying global variables inside and outside a function:
# Global variable
total = 50
def add_to_total(amount):
global total # Declare that we are using the global variable
total += amount # Modify the global variable
def print_total():
# Accessing the global variable inside the Function
print(f”Total inside function: {total}”)
# Accessing the global variable outside the Function
print(f”Total before function call: {total}”) # Output: 50
# Modify the global variable inside the Function
add_to_total(30)
# Accessing the global variable outside the Function after modification
print(f”Total after function call: {total}”) # Output: 80
# Accessing the global variable inside another function
print_total() # Output: Total inside Function: 80
Best practices on how to use global variables in Python
Important Article: What is the Difference Between Framework vs Library
Conclusion
Variables in Python are essential elements that, when judiciously used, can help you write clear and bug-free code. Global variables are powerful tools in Python that should be used with caution. By naming them clearly, minimizing their use, and correctly documenting and thoroughly testing your code, you can handle global variables while keeping your code clean and maintainable.
Learn Python with Kochiva and get ready for a career in tech. Our expert trainers will teach you everything you need to know in the field of IT, and help you find a job.
Want more information? contact Kochiva now!
Read more informative blog: Best Python Training Institutes in India
Best Online Spanish Classes in India
Best Online German Classes in India
Best Online French Classes in India
Top 10 German Course in Cologne
German c1 course
CEFR Language Levels – Common European Framework of Reference for Languages
Request a Call Back
Related Posts
Top 10 German Course in Cologne
Read MoreTaking up a German course in Cologne can help set you apart from the crowd and take advantage of world-class education and professional growth. German is one of the most widely spoken languages in the world. Recruiters in Cologne often see the benefits in having an applicant who is able to interact with co-workers in […]
German c1 course
Read MoreThe German C1 Online Course at Kochiva is designed for learners who want to master the language at an advanced level. This course enables you to communicate fluently, understand complex texts, and express ideas clearly in professional and academic settings. At the C1 level, you will develop near-native proficiency, allowing you to read, write, and […]
CEFR Language Levels – Common European Framework of Reference for Languages
Read MoreCEFR Language Levels: The Council of Europe created the Common European Framework of Reference for Languages (CEFR). The goal was to guarantee transparency and comparability in language proficiency, application, and acquisition among students in Europe. In this article, we will tell you everything related to CEFR levels and why it is important to know about […]
TELC B1 Exam Preparation: Everything You Need to Know
Read MoreTELC B1 Exam Preparation: The TELC (The European Language Certificates) exam is a standardized test designed to assess language proficiency across different levels, from A1 to C2. It is widely recognized by universities, employers, and government institutions across Europe. If you are planning to take the TELC B1 exam, you might be wondering about the […]
TELC A1 Exam Preparation
Read MoreAre you looking for the best TELC A1 exam preparation strategies to ace your test with confidence? So, here’s your ultimate TELC A1 Exam Preparation Guide! Whether you’re taking the exam for personal development, work, or immigration, knowing the fundamentals of the German language is the key to success. The TELC A1 is your gateway […]
Meet Our Conversion Expert