Reputation: 13
It seems that many get this error but each situation is different.
My code:
i = 0
def sort(a):
b = len(a)
if(i == b):
print (a)
elif(b == 0):
print ('Error. No value detected...')
elif(b == 1):
print (a)
elif(a[i]>a[i+1]):
a[i], a[i+1] = a[i+1], a[i]
i = i + 1
print(a)
sort(a)
Error Code:
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
File "(File location, you don't need to know....)", line 8, in sort
if(i == b):
UnboundLocalError: local variable 'i' referenced before assignment
I am not sure what this error means or what is wrong.
Upvotes: 1
Views: 13990
Reputation: 1190
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 = 0
def 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 = 0
def foo():
i = 1
print 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 = 0
def 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)
Upvotes: 2
Reputation: 1741
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.
Upvotes: 0
Reputation: 11
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.
Upvotes: 1
Reputation: 184405
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.
Upvotes: 1