问题描述
似乎很多人都会收到此错误,但每种情况都不同.香港专业教育学院搜索了一段时间,但我不知道如何针对我的情况使用它.我甚至试图获得现场帮助...
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...
我的代码:
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)
错误代码:
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
对不起,我对代码块不太熟悉.
Sorry im not familiar with the code block thingy..
我不确定此错误是什么意思还是什么错误...
Im not sure what this error means or whats wrong...
非常感谢.
推荐答案
您的变量 i
是在全局(模块)级别定义的.请参阅作用域规则的简短说明?有关信息,python查找变量的顺序.如果仅尝试从函数中引用变量,则不会收到错误:
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()
由于没有局部变量 i
,因此将找到并使用全局变量.但是,如果您在函数中分配 i
,则会创建一个局部变量:
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
请注意,全局变量未更改.在您的情况下,您包括行 i = i + 1
,从而创建了一个局部变量.但是,您尝试在为其分配任何值之前先引用该变量.这说明了您得到的错误:
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()
要么在函数中声明 global i
,以告诉python使用全局变量而不是创建局部变量,要么完全重写代码(因为它不能像我怀疑的那样执行确实)
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)
这篇关于错误代码:UnboundLocalError:分配前引用的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!