Skip to main content

Command Palette

Search for a command to run...

What is UnboundLocalError in Python?

Published
2 min readView as Markdown
What is UnboundLocalError in Python?
A

Passionate Software Developer | Crafting clean code and elegant solutions

This error occurs when you try to use a local variable in a function before assigning a value to it.

⚠️ Error Example:

pythonCopy codex = 5

def my_func():
    print(x)  # Trying to access x
    x = 10    # Local assignment

my_func()

Output:

UnboundLocalError: local variable 'x' referenced before assignment

Why Does This Error Happen?

In Python, if you assign a value to a variable anywhere in a function, Python treats it as a local variable throughout the function.

So in the example above, Python thinks x is a local variable, but we’re trying to print it before assigning a value.


✅ How to Fix It

✅ Solution 1: Use global keyword

If you want to access and modify a global variable, declare it with global:

pythonCopy codex = 5

def my_func():
    global x
    print(x)
    x = 10

my_func()
print("After:", x)

✅ Solution 2: Pass the variable as an argument

This is safer and more Pythonic than using global.

pythonCopy codex = 5

def my_func(x):
    print(x)
    x = 10
    return x

x = my_func(x)
print("After:", x)

✅ Best Practice

Try to avoid using global variables unless necessary. It’s cleaner and safer to pass variables into functions.


💡 Bonus Tip: Local vs Global Variable Rules

Variable ScopeDefined Outside FunctionAssigned Inside Function
Global✅ AccessibleUnboundLocalError unless declared global
Local❌ Not accessible✅ Assigned normally

🧪 Test Your Understanding

What will the following code print?

pythonCopy codecount = 0

def increment():
    count += 1
    print(count)

increment()

Hint: You’ll get the same UnboundLocalError.

✅ Try fixing it using either global count or passing count as an argument.


🚀 Conclusion

UnboundLocalError is one of those errors that seems confusing at first, but once you understand Python’s scoping rules, it becomes easy to fix.

The golden rule: If you assign a variable inside a function, Python assumes it’s local.

More from this blog

D

Dev Insights

26 posts