Last modified: Oct 28, 2026

Python Global and Local Variables

Understanding variable scope is crucial for writing clean and maintainable Python code. Variables in Python can be classified into two main types based on their scope: global variables and local variables. This distinction helps developers manage data flow and prevent unexpected behavior in their programs.

What Are Global Variables?

Global variables are defined outside any function or block. They can be accessed from anywhere in the program, including inside functions. This makes them useful for storing values that need to be shared across multiple parts of your code.


# Defining a global variable
message = "Hello, World!"

def print_message():
    # Accessing the global variable inside a function
    print(message)

print_message()

Hello, World!

In this example, the variable message is declared outside the function print_message(). It can be accessed directly within the function without any special declaration.

What Are Local Variables?

Local variables are defined inside a function. Their scope is limited to that function only. Attempting to access them outside their defining function will result in a NameError.


def greet():
    # Defining a local variable
    greeting = "Welcome!"
    print(greeting)

greet()
# Trying to access the local variable outside the function
# print(greeting)  # This would raise a NameError

Welcome!

The variable greeting exists only within the greet() function. If you try to use it elsewhere, Python will not recognize it.

The Scope Rules in Python

Python follows the LEGB Rule when resolving variable names:

  1. Local – Variables defined inside the current function.
  2. Enclosing – Variables in the local scope of enclosing functions (used in nested functions).
  3. Global – Variables defined at the top level of the script or module.
  4. Built-in – Predefined names in Python like print(), len(), etc.

These rules determine how Python searches for a variable when it's referenced in your code.

Using the global Keyword

By default, Python treats variables assigned inside a function as local. To modify a global variable within a function, you must declare it as global using the global keyword.


# Global variable
counter = 0

def increment():
    global counter  # Declare that we're using the global variable
    counter += 1
    print("Counter:", counter)

increment()
increment()

Counter: 1
Counter: 2

Without the global keyword, Python would create a new local variable instead of modifying the global one, leading to incorrect results.

Common Mistakes with Variable Scope

A common mistake is trying to use a global variable inside a function without declaring it as global. This leads to an UnboundLocalError because Python sees the assignment and assumes the variable is local.


value = 10

def update_value():
    # This will cause an UnboundLocalError
    value = value + 5
    print(value)

# update_value()  # Uncommenting this line will raise an error

To fix this issue, explicitly declare the variable as global:


value = 10

def update_value():
    global value
    value = value + 5
    print(value)

update_value()

15

Nested Functions and the nonlocal Keyword

When working with nested functions, you might encounter situations where you want to modify a variable from an enclosing function. In such cases, the nonlocal keyword comes in handy.


def outer_function():
    name = "Alice"

    def inner_function():
        nonlocal name  # Refers to the variable in the enclosing scope
        name = "Bob"
        print("Inside inner_function:", name)

    inner_function()
    print("Inside outer_function:", name)

outer_function()

Inside inner_function: Bob
Inside outer_function: Bob

The nonlocal keyword allows the inner function to modify the variable defined in the outer function. This is different from global, which refers to module-level variables.

Best Practices for Managing Scope

Managing variable scope properly improves code readability and reduces bugs. Here are some best practices:

  • Minimize the use of global variables. They can make debugging harder and lead to naming conflicts.
  • Use function parameters and return values to pass data instead of relying on globals.
  • Always declare variables as global or nonlocal when modifying them inside functions.
  • Keep variable names descriptive and unique to avoid confusion.

Following these guidelines helps ensure your Python code remains modular and easy to maintain.

Real-World Example: Counter Class

Let’s look at a practical example that demonstrates how scope works in a class context:


class Counter:
    # Class-level variable (shared among all instances)
    total_instances = 0

    def __init__(self):
        self.count = 0  # Instance variable
        Counter.total_instances += 1  # Modifying class variable

    def increment(self):
        self.count += 1

    def show_count(self):
        print("Instance count:", self.count)

# Creating instances
c1 = Counter()
c2 = Counter()

c1.increment()
c2.increment()
c2.increment()

c1.show_count()  # Output: Instance count: 1
c2.show_count()  # Output: Instance count: 2

print("Total instances created:", Counter.total_instances)

Instance count: 1
Instance count: 2
Total instances created: 2

This example shows how class-level variables behave differently from instance variables. The total_instances variable is shared across all instances, while count is unique to each object.

Connecting Concepts: Loops and Conditionals

Variable scope also interacts with control structures like loops and conditionals. For instance, variables defined inside a Python For Loop and While Loop Explained remain accessible after the loop ends.


for i in range(3):
    result = i * 2
    print(result)

print("Final value of i:", i)
print("Final value of result:", result)

0
2
4
Final value of i: 2
Final value of i: 4

Similarly, in conditional blocks, variables defined inside an Python If Else Statements: A Beginner Guide are accessible outside the block.


x = 5
if x > 0:
    status = "Positive"
print(status)

Positive

Unlike many other programming languages, Python does not create a new scope for loops and conditionals. This behavior can sometimes lead to unintended side effects if you’re not careful.

Conclusion

Grasping the concept of global and local variables is fundamental to mastering Python. By understanding how scope works and using keywords like global and nonlocal appropriately, you can write more predictable and robust code. Remember to follow best practices, avoid unnecessary global variables, and always test your assumptions about variable accessibility. Whether you're working with simple scripts or complex applications, proper scope management will serve you well in your Python journey.