The error message “local variable is referenced before assignment” is one of the most common and confusing issues Python beginners encounter. Also, it usually appears as UnboundLocalError: local variable 'name' referenced before assignment, and it stops your program at the exact line where Python tries to read a variable that has not yet received a value inside a function. The confusing part is that the variable may exist outside the function, or it may be assigned later in the same function, so the code looks correct at first glance. Understanding why Python treats the variable as local, and how to fix the problem safely, is essential for writing reliable Python programs Easy to understand, harder to ignore. Worth knowing..
What Does “Local Variable Referenced Before Assignment” Mean?
In Python, a local variable is a variable that belongs to a specific function scope. Day to day, it is created when a function runs and is normally destroyed when the function finishes. The error “local variable referenced before assignment” means that Python has decided a name is local to a function, but the function tries to use that name before any value has been assigned to it.
Quick note before moving on Worth keeping that in mind..
Consider this example:
count = 10
def show_count():
print(count)
count = 5
show_count()
At first glance, this code seems to print 10. Instead, Python raises:
UnboundLocalError: local variable 'count' referenced before assignment
The reason is subtle but important: because count = 5 appears anywhere inside show_count(), Python marks count as a local variable for the entire function. Also, the print(count) line runs before the local count has been assigned, so Python cannot read it. The global count = 10 is ignored inside that function unless you explicitly tell Python otherwise And it works..
Why Python Raises This Error
Python decides variable scope before the function actually runs. During compilation, it scans the function body and notes every name that is assigned. If a name is assigned anywhere inside the function, Python treats that name as local throughout the whole function. This design prevents accidental changes to global variables, but it also creates the “referenced before assignment” error when the order of operations is wrong.
The key rule is simple:
- Reading a variable does not make it local.
- Assigning to a variable anywhere in a function makes it local for that entire function.
- If the function reads the variable before the local assignment executes, Python raises
UnboundLocalError.
This is why the error can appear even when a global variable with the same name exists. Python is not looking at the global variable; it is looking for a local variable that has not been created yet.
Common Causes and Examples
1. Using a Global Variable Without global
The most common cause is trying to modify or read a global variable inside a function while also assigning to it. The fix is to use the global keyword when you genuinely intend to modify a module-level variable:
count = 10
def show_count():
global count
print(count)
count = 5
show_count()
Now Python knows that count refers to the global variable, not a new local one. On the flip side, global should be used carefully. In most cases, passing values as parameters and returning results is cleaner and easier to test That's the part that actually makes a difference..
2. Conditional Assignment
Another frequent cause is assigning a variable only inside an if branch:
def get_status(is_active):
if is_active:
status = "active"
return status
Calling get_status(False) raises the error because status is assigned only when is_active is true. The fix is to initialize the variable before the condition:
def get_status(is_active):
status = "inactive"
if is_active:
status = "active"
return status
This pattern makes the function’s behavior explicit and prevents the variable from being unbound And that's really what it comes down to..
3. Assignment After Use in a Loop
A variable may be read before it is assigned inside a loop:
def calculate_total(values):
for value in values:
total = total + value
return total
Here, `total
is referenced on the right-hand side before any value has been assigned to it. On the first iteration, Python tries to read total to add value to it, but total does not exist yet, so the error is raised. The fix is to initialize the accumulator before the loop begins:
def calculate_total(values):
total = 0
for value in values:
total = total + value
return total
This is a common pattern for building up a result, and initializing the accumulator to a sensible starting value (0 for sums, 1 for products, an empty list for collections) resolves the error cleanly.
4. Reading a Variable in a Nested Function
Closures can also trigger this error when an inner function assigns to a name that the outer scope expects to reuse:
def outer():
message = "hello"
def inner():
print(message)
message = "world"
inner()
Because inner assigns to message, Python treats it as local to inner, and the earlier print fails. Adding nonlocal message inside inner tells Python to bind to the enclosing function's variable instead of creating a new local one Practical, not theoretical..
How to Diagnose the Error
When you encounter UnboundLocalError, the traceback points to the exact line where the read happened. Work through it methodically:
- Check for any assignment to the variable name anywhere in the function, including inside branches, loops, or nested functions.
- Determine the intended scope. If the variable should be shared across the module, use
global. If it belongs to an enclosing function, usenonlocal. If it is genuinely local, initialize it before first use. - Prefer parameters and return values over shared state. Passing data in and returning results out eliminates most scope-related bugs and makes functions easier to reason about and test.
Conclusion
The UnboundLocalError is fundamentally a symptom of a mismatch between where Python thinks a variable lives and where you intended it to live. Because Python determines scope at compile time based on assignment, a single assignment anywhere in a function can turn a name local for the entire function, even in code paths that run before the assignment. So naturally, understanding this rule removes most of the mystery: read the traceback, locate the assignment that made the name local, and decide whether the variable should be local, global, or nonlocal. That said, in practice, the cleanest fix is often to initialize variables before use and to favor explicit parameters and return values over mutable shared state. Once you internalize how Python resolves names, this error becomes easy to spot and even easier to prevent.
This is where a lot of people lose the thread.
Quick Reference: Scope Declaration Cheatsheet
| Keyword | Scope Target | Typical Use Case | Side Effect |
|---|---|---|---|
| (none) | Local (current function) | Standard temporary variables | Assignment creates a new local name. But |
global |
Module (global) | Modifying module-level constants/state | Assignment modifies the module-level binding. |
nonlocal |
Enclosing function | Modifying state in a closure factory | Assignment modifies the variable in the nearest enclosing def. |
It sounds simple, but the gap is usually here.
Keep this table handy during code reviews; a quick glance often reveals whether a global declaration is truly necessary or if a refactor toward parameter passing would be cleaner.
Related Errors to Distinguish
It is easy to confuse UnboundLocalError with its siblings. Knowing the difference speeds up debugging:
NameError: name 'x' is not defined: The namexdoes not exist anywhere in the accessible scopes (local, enclosing, global, built-in). You likely have a typo or forgot to import/define the variable entirely.UnboundLocalError: local variable 'x' referenced before assignment: The namexdoes exist as a local variable (because you assign to it somewhere in the function), but you tried to read it before that assignment executed.SyntaxError: name 'x' is used prior to global declaration: You wroteglobal xafter you already usedxin the function body. Move theglobalstatement to the top of the function.
Final Thoughts
Mastering Python’s scoping rules—specifically the LEGB resolution order (Local, Enclosing, Global, Built-in) and the compile-time binding decision triggered by assignment—transforms UnboundLocalError from a frustrating mystery into a clear signal about data flow. The error is not a bug in the interpreter; it is the interpreter correctly enforcing the contract you implicitly wrote when you placed an assignment statement inside a function Simple, but easy to overlook..
The most reliable codebases treat this error as a design smell. Explicit data flow beats implicit shared state almost every time. Worth adding: if you find yourself reaching for global or nonlocal frequently, consider whether a class, a dataclass, or a simple function accepting arguments and returning a tuple would express the intent more clearly. By initializing accumulators, passing context explicitly, and reserving scope modifiers for the rare cases where they are genuinely warranted, you eliminate this entire class of runtime errors before they ever reach production The details matter here..