I am trying to figure out this:
c = 1 def f(n): print c + n def g(n): c = c + n f(1) # => 2 g(1) # => UnboundLocalError: local variable 'c' referenced before assignment
Thanks!
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 .
UnboundLocalError can be solved by changing the scope of the variable which is complaining. You need to explicitly declare the variable global. Variable x's scope in function printx is global. You can verify the same by printing the value of x in terminal and it will be 6.
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.
In Python or any other programming languages, the definition of local variables remains the same, which is “A variable declared inside the function is called local function”. We can access a local variable inside but not outside the function.
Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the global
statement:
def g(n): global c c = c + n
This is one of the quirky areas of Python that has never really sat well with me.
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