How to Fix Local Variable Referenced Before Assignment Error in Python
Table of Contents
In Python, when you try to reference a variable that hasn't yet been given a value (assigned), it will throw an error.
That error will look like this:
BASHlocal variable referenced before assignment
In this post, we'll see examples of what causes this and how to fix it.
Fixing local variable referenced before assignment error
Let's begin by looking at an example of this error:
PYTHONvalue = 1
def increment():
value = value + 1
print(value)
increment()
If you run this code, you'll get
BASHUnboundLocalError: local variable 'value' referenced before assignment
The issue is that in this line:
PYTHONvalue = value + 1
We are defining a local variable called value
and then trying to use it before it has been assigned a value, instead of using the variable that we defined in the first line.
If we want to refer the variable that was defined in the first line, we can make use of the global
keyword.
The global
keyword is used to refer to a variable that is defined outside of a function.
Let's look at how using global
can fix our issue here:
PYTHONvalue = 1
def increment():
global value
value = value + 1
print(value)
increment()
Global variables have global scope, so you can referenced them anywhere in your code, thus avoiding the error.
If you run this code, you'll get this output:
BASH2
Conclusion
In this post, we learned at how to avoid the local variable referenced before assignment
error in Python.
The error stems from trying to refer to a variable without an assigned value, so either make use of a global variable using the global
keyword, or assign the variable a value before using it.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase