Skip to content Skip to sidebar Skip to footer

Error Code: Unboundlocalerror: Local Variable Referenced Before Assignment

It seems that many get this error but each situation is different. Ive search somewhat long, but i dont understand how to use it for my situation.. I tried to get live help even...

Solution 1:

Your variable i is defined at the global (module) level. See Short Description of the Scoping Rules? for info the order in which python looks for your variable. If you only try to reference the variable from within your function, then you will not get the error:

i = 0def foo():
    print i

foo()

Since there is no local variable i, the global variable is found and used. But if you assign to i in your function, then a local variable is created:

i = 0def foo():
    i = 1print i

foo()
print i

Note that the global variable is unchanged. In your case you include the line i = i + 1, thus a local variable is created. But you attempt to reference this variable before it is assigned any value. This illustrates the error you are getting:

i = 0def foo():
    print i
    i = 1

foo()

Either declare global i within your function, to tell python to use the global variable rather than creating a local one, or rewrite your code completely (since it does not perform as I suspect you think it does)

Solution 2:

Since you assign to it, your variable i is a local variable in your sort() function. However, you are trying to use it before you assign anything to it, so you get this error.

If you intend to use the global variable i you must include the statement global i somewhere in your function.

Solution 3:

your function doesn't have access to the variable i. Define i INSIDE the function. Also, if i = 0, and you want a branch for if b==i why do you need a separate branch for elif b==0? Just curious.

Solution 4:

Actually, every situation with this bug is the same: you are defining a variable in a global context, referencing it in a local context, and then modifying it later in that context. When Python interprets your function, it identifies all variables you modify in the function and creates local versions of them. Since you don't assign to i until after you modify it, you reference an undefined local variable.

Either define i inside the function or use global i to inform Python you wish to act on the global variable by that name.

Post a Comment for "Error Code: Unboundlocalerror: Local Variable Referenced Before Assignment"