Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python scope: "UnboundLocalError: local variable 'c' referenced before assignment" [duplicate]

Tags:

python

scope

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!

like image 522
all-too-human Avatar asked Sep 28 '08 17:09

all-too-human


People also ask

How do you fix UnboundLocalError local variable referenced before assignment?

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 .

How do you fix UnboundLocalError?

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.

What does UnboundLocalError mean?

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.

How do you declare a local variable in Python?

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.


1 Answers

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.

like image 59
Greg Hewgill Avatar answered Oct 09 '22 12:10

Greg Hewgill