What am I doing wrong here?
counter = 0 def increment(): counter += 1 increment()
The above code throws an UnboundLocalError
.
The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.
The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function. To solve the error, mark the variable as global in the function definition, e.g. global my_var .
Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.
In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.
Python doesn't have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line
counter += 1
implicitly makes counter
local to increment()
. Trying to execute this line, though, will try to read the value of the local variable counter
before it is assigned, resulting in an UnboundLocalError
.[2]
If counter
is a global variable, the global
keyword will help. If increment()
is a local function and counter
a local variable, you can use nonlocal
in Python 3.x.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With