Fundamentals 12 min read

Mastering Global vs Local Variables in Python: Key Differences & Best Practices

This article explains the distinction between global and local variables in Python, demonstrates how to use the global keyword to modify variables across scopes, provides detailed examples, best‑practice guidelines, common pitfalls, and exercises to help you write cleaner, more maintainable code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Mastering Global vs Local Variables in Python: Key Differences & Best Practices

Understanding Global and Local Variables

Learn the difference between global variables and local variables in Python and how to manage variable scope using the global keyword for high‑quality, maintainable code.

1. Basic Concepts of Global Variables

Definition : Variables defined outside any function are called global variables.

Scope : The entire program, including all functions and code blocks, can access and read a global variable.

Lifecycle : From the moment they are defined until the program terminates.

2. Basic Concepts of Local Variables

Definition : Variables defined inside a function are called local variables.

Scope : Only the function in which they are defined can access them; they are invisible outside the function.

Lifecycle : Created when the function is called and destroyed when the function finishes execution.

3. Example 1: Basic Usage

# Global variable
global_var = "I am a global variable"

def my_function():
    # Local variable
    local_var = "I am a local variable"
    print("Inside function - global:", global_var)
    print("Inside function - local:", local_var)

my_function()
print("Outside function - global:", global_var)

Output :

Inside function - global: I am a global variable
Inside function - local: I am a local variable
Outside function - global: I am a global variable

Explanation : The function can read the global variable directly, while the local variable is only accessible inside the function. Attempting to read local_var outside would raise a NameError.

4. Example 2: Modifying a Global Variable Without global

# Global variable
counter = 10

def increment_counter():
    counter = 20  # Creates a new local variable, does not modify the global one
    print("Inside function - counter:", counter)

increment_counter()
print("Outside function - counter:", counter)

Output :

Inside function - counter: 20
Outside function - counter: 10

Explanation : Assigning to counter inside the function creates a new local variable that shadows the global one. The global counter remains unchanged.

5. Using the global Keyword

Syntax

def function_name():
    global variable_name
    # Now you can read and modify the global variable

Example 3: Modifying a Global Variable

# Global variable
counter = 10

def increment_counter():
    global counter
    counter += 1
    print("Inside function - counter:", counter)

increment_counter()
print("Outside function - counter:", counter)

Output :

Inside function - counter: 11
Outside function - counter: 11

6. Best‑Practice Recommendations

Avoid overusing global variables; they are visible everywhere and can cause unpredictable side effects.

Prefer local variables and pass data via function parameters and return values for better modularity.

Use global variables only when multiple functions truly need to share mutable state (e.g., configuration, counters, flags).

When you need to modify a global variable inside a function, declare it with global to make your intent explicit.

7. Summary of Key Points

Global Variable : Defined outside functions, scope = entire program, lifecycle = program run.

Local Variable : Defined inside functions, scope = function only, lifecycle = function call.

global Keyword : Declares a name as global inside a function, allowing read/write access to the global variable.

Best Practice : Minimize global usage; use locals, parameters, and returns for clean code.

8. Frequently Asked Questions

Q1: Why must the global keyword be used to modify a global variable inside a function?

Without global, Python treats any assignment as creating a new local variable, leaving the global unchanged. Declaring global tells Python you intend to work with the variable in the global scope.

Q2: How can I read a global variable inside a function without modifying it?

You can simply reference the variable; no global declaration is needed for read‑only access.

Q3: Can global and local variables share the same name?

Yes, but the local variable will shadow the global one inside its function, which is generally discouraged.

9. Exercises

Basic Exercise

number = 5  # Global variable

def increment():
    global number
    number += 1
    print("Inside function - number:", number)

increment()
print("Outside function - number:", number)

Advanced Exercise

text = "Hello"  # Global variable

def append_text(new_text):
    global text
    text += new_text
    print("Inside function - text:", text)

append_text(" World")
print("Outside function - text:", text)

Challenge Exercise

items = []  # Global list

def add_item(item):
    global items
    items.append(item)
    print(f"Added: {item}")

add_item("Apple")
add_item("Banana")
add_item("Cherry")
print("Final items list:", items)
Pythonscopeglobal variableslocal variablescoding practice
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.