Of course! The "global name" error in Python is a very common and important concept to understand. It's a NameError, and it happens when you try to use a variable name that Python cannot find in the current scope.

Let's break it down from the ground up.
The Core Concept: Scope
In Python, variables only exist within a certain "scope". Think of it like a set of nested boxes:
- Local Scope: The innermost box. This is inside a function. Variables created here only exist while the function is running.
- Enclosing Scope: A box that contains the local scope. This is for nested functions.
- Global Scope: The outermost box. This is at the top level of your Python file (
.py). Variables created here are accessible from anywhere in that file. - Built-in Scope: A special, universal box that contains Python's built-in names (like
print,len,str).
Python searches for a variable's name in this order: Local -> Enclosing -> Global -> Built-in. This is called the LEGB rule.
The global name 'X' is not defined error occurs when you try to use a variable inside a function (Local Scope), but:

- It doesn't exist as a local variable in that function.
- It doesn't exist in any enclosing scopes.
- It doesn't exist in the Global Scope.
- It's not a built-in function.
The Problem: Trying to Read a Global Variable Inside a Function
This is the most common scenario where the error occurs. You have a variable defined outside a function, and you try to use it inside the function.
Incorrect Code (Causing the Error):
# This variable is in the GLOBAL scope
my_global_variable = 10
def modify_variable():
# Python looks for 'my_global_variable' in the LOCAL scope of this function.
# It doesn't find it there.
# It then looks in the GLOBAL scope and finds it.
# However, the next line tries to ASSIGN to it, which is the problem.
my_global_variable = my_global_variable + 5 # This will cause an error!
print(f"Before function call: {my_global_variable}")
modify_variable()
print(f"After function call: {my_global_variable}")
When you run this, you get:
Before function call: 10
Traceback (most recent call last):
File "your_script_name.py", line 9, in <module>
modify_variable()
File "your_script_name.py", line 5, in modify_variable
my_global_variable = my_global_variable + 5
UnboundLocalError: local variable 'my_global_variable' referenced before assignment
Note: Python actually raises an
UnboundLocalErrorin this specific case, which is a subtype ofNameError. The core issue is the same: a misunderstanding of scope.
Why does this happen?
The moment Python sees an assignment () to a name inside a function, it decides that name must be a local variable for that function. When it then tries to read the value of my_global_variable on the right side of the sign, it looks for it in the local scope and can't find it because it hasn't been created yet. Hence, the error.
The Solution 1: The global Keyword
To tell a function that you want to use a variable from the global scope (and also modify it), you must explicitly declare it with the global keyword.
Correct Code (Using global):
# This variable is in the GLOBAL scope
my_global_variable = 10
def modify_variable():
# Tell Python: "The 'my_global_variable' I'm about to use is the GLOBAL one."
global my_global_variable
my_global_variable = my_global_variable + 5
print(f"Before function call: {my_global_variable}")
modify_variable()
print(f"After function call: {my_global_variable}")
Output:
Before function call: 10
After function call: 15
This works perfectly. The global keyword tells the function to bypass the local scope rules and work directly with the global variable.
Solution 2: Just Reading a Global Variable (No global Needed)
If you only need to read the value of a global variable inside a function and not change it, you don't need the global keyword.
Correct Code (Reading Only):
# This variable is in the GLOBAL scope
message = "Hello, World!"
def read_message():
# We are only READING the value, not assigning to it.
# Python finds 'message' in the global scope and uses it.
print(f"Inside the function: {message}")
read_message()
print(f"Outside the function: {message}")
Output:
Inside the function: Hello, World!
Outside the function: Hello, World!
Solution 3: The Best Practice - Passing Arguments and Returning Values
Using the global keyword is often considered bad practice because it makes functions less predictable and harder to test (they have "side effects" by changing global state). The more "Pythonic" way is to pass data into functions as arguments and get data back via a return value.
Recommended Code (Using Arguments and Return):
def add_five_to_number(number_to_modify):
# This function is self-contained. It doesn't care about any global variables.
# It takes an input, does its job, and returns a result.
return number_to_modify + 5
# Define our data in the global scope
my_number = 10
# Pass the global variable into the function and capture the returned value
new_number = add_five_to_number(my_number)
print(f"Original number: {my_number}")
print(f"New number after function call: {new_number}")
Output:
Original number: 10
New number after function call: 15
This approach is much cleaner, more reusable, and easier to debug.
Summary Table
| Scenario | Code Example | Result | Best Practice? |
|---|---|---|---|
| Read Global Variable | def f(): print(g_var) |
Works fine | Yes |
| Modify Global Variable (Incorrect) | def f(): g_var = g_var + 1 |
UnboundLocalError |
No |
| Modify Global Variable (Correct) | def f(): global g_var; g_var = g_var + 1 |
Works, but modifies global state | Sometimes |
| Modify Data (Recommended) | def f(x): return x + 1 new_val = f(g_var) |
Works, clean, no side effects | Yes |
Quick Checklist for NameError
- Did you typo the variable name? (e.g.,
my_varvsmy_vr) - Is the variable defined before you try to use it?
- Are you trying to modify a variable inside a function?
- If yes, did you forget to declare it
global? - If yes, could you refactor to pass it as an argument instead? (This is usually better).
- If yes, did you forget to declare it
