Python Global Variables

Global and Local Variables in Python

April 6th, 2026
2796
8:00 Minutes

Global Variables in Python is a variable defined outside of any function or class, which makes it accessible from anywhere within the program. It has a global scope that means its value can be read and used by all functions and even across different  Python modules or larger applications organized using Python packages. Isn't it an amazing feature? Do you want to learn more about it?

Whether you are a beginner to programming or a professional Python Developer, it can be a great Python skill for your resume. This article aims to provide a comprehensive understanding into the Python Global Variables along with ways to use and create them. This guide also compares it with local variables and provides an inclusive cheat sheet for a quick understanding.

These insights are suggested by the top experienced professionals and help you achieve great career heights. Let's dive in to become a proficient Python Developer.

What are Global Variables in Python?

Global variables in Python are defined outside the functions which can be accessed anytime or anywhere in the program when required. These have a specific scope, meaning by which developers can access them. This feature is what makes them different from the local variables. It is also important to use them precisely as overuse can make the code complicated.

Master Python Programming with Python Training

Boost your coding skills and gain hands-on knowledge in Python.

Explore Now

Use of Global Variables in Python: Applications Explained

Understanding the use of variables in Python is also essential as overuse can lead to complications or naming disputes in the program. There are many situations where developers can use these variables. Some of them necessarily require these usages and others don't. The following are the scenarios where the use of global variables is very important:

  • Configurations & settings: Useful when developers need to apply configuration or settings to an entire program.
  • Small utility scripts: Useful to create small scripts where automation and simplicity are important.
  • Caching data: Developers can use global variables to store cached data for performance improvements.
Also Explore: Data Types in Python

How to Create a Global Variable in Python?

Creating Global variables in Python is straightforward: define them at the top (module level). The code below uses two global variables:

# Define global variables
my_global_variable_1 = 100
my_global_variable_2 = "Hello, World!"

def my_function():
    # Access global variables
    print(my_global_variable_1)
    print(my_global_variable_2)

# Call the function
my_function()

# Modify a global variable from within a function
def modify_global_variable():
    global my_global_variable_1
    my_global_variable_1 = 20

modify_global_variable()

# Now my_global_variable_1 has been modified
print(my_global_variable_1)

Output:

100
Hello, World!
20

Explanation:

This code has two global variables: my_global_variable_1 and my_global_variable_2. Both are defined at the top of the script and are accessed inside Python functions like my_function(). To modify a global variable from within a function, you must declare it with the global keyword (as shown).

Related Article: Best Python Libraries

Scope of Variable in Python: Explained in Details

Scope of variables in Python is the context or area in which developers can declare or access them. It decides guidelines on how one can use or access them. Python commonly uses local and global scopes.

1. Local Scope

Local scope includes variables available only within a particular function or block. These are not accessible outside that function and they cease to exist after function execution. Example:

# Define a function with a local variable
def calculate_square(number):
    result = number * number  # 'result' is a local variable
    return result

# Call the function
square_of_5 = calculate_square(5)

# Print the result
print(f"The square of 5 is: {square_of_5}")

Output:

The square of 5 is: 25

2. Global Scope

Global scope includes variables defined at the top of the module and not inside any function. They can be accessed by any function in the module. Use the global keyword to modify them inside functions.

# Define a global variable to keep track of the counter
counter = 0

def increment_counter():
    global counter  # use global variable
    counter += 1

def display_counter():
    print(f"Current counter value: {counter}")

# Simulate button clicks
print("Simulating button clicks:")
increment_counter()
display_counter()

increment_counter()
display_counter()

increment_counter()
display_counter()

# Reset counter
def reset_counter():
    global counter
    counter = 0

print("After resetting counter:")
reset_counter()
display_counter()

Output:

Simulating button clicks:
Current counter value: 1
Current counter value: 2
Current counter value: 3
After resetting counter:
Current counter value: 0
Also Read: Data Structures in Python

Difference Between Local and Global Variables in Python

Local and global variables serve similar purposes but differ in scope, lifetime, and access.

Basis Global Variables Local Variables
Definition Defined outside the function. Defined inside the function.
Declaration Use global to modify inside a function. No specific keyword needed.
Lifetime Exist throughout program execution. Exist only during function execution.
Accessibility Accessible to all functions in the module. Accessible only within the function.
Value Changes reflect across the code. Changes do not affect other functions.
Data Sharing Possible Not possible
Best Practice Limit use of globals; prefer args/returns or class attributes. Encourages modular code.
Also Explore: Python Interview Questions and Answers

Python Global Variables Cheat Sheet

If you want a quick reference for other core concepts, you can also review our Python cheat sheet. Short overview and examples:

Name Description Use / Example
Global Variable Declared outside functions, accessible everywhere. x = 10
Accessing Global Read inside a function by default. def show(): print(x)
global keyword Allows modifying a global variable inside a function. global x; x = 20
globals() Built-in dict storing module globals. globals()['x']
Best Practice Limit use; prefer args/returns or class attributes. Clean, modular code

Learn AI with Python with Our Latest Training Program

Boost your coding skills and gain hands-on knowledge in AI with Python.

Explore Now

Wrapping Up

We have explored many things about global variables in Python. They are useful when applied properly but over-reliance can cause problems. For a deeper understanding, explore our Python tutorial.

Also Explore: Python MCQs

FAQs on Global Variables in Python

Q1. What is a constant variable in Python?

A constant variable is a value that should not change during the program. Python has no enforced constants; by convention you use UPPERCASE names.

Q2. What is static value in Python?

A static value usually refers to a class variable shared among all instances in Python classes and objects. It is defined inside the class body but outside instance methods.

Q3. What if I extensively use global variables in Python?

Overuse may lead to unintended modifications, harder debugging, reduced modularity, name collisions, and poor encapsulation.

Q4. Why is the globals() function used in Python?

globals() is used to see or access all global variables in a program. It returns them in a dictionary format so you can check or change global values while the program is running.

About the Author
Sanjay Prajapat
About the Author

Sanjay Prajapat is a Data Engineer and technology writer with expertise in Python, SQL, data visualization, and machine learning. He simplifies complex concepts into engaging content, helping beginners and professionals learn effectively while exploring emerging fields like AI, ML, and cybersecurity in today’s evolving tech landscape.

Drop Us a Query
Fields marked * are mandatory

Programming Certification Courses

×

Your Shopping Cart


Your shopping cart is empty.