UnBoundLocalError:赋值之前引用的局部变量(Python) [英] UnBoundLocalError: local variable referenced before assignment (Python)
问题描述
我正在尝试创建一个返回值servo_quadrant
的函数servo_to_quadrant
.
I'm trying to create a function servo_to_quadrant
that returns the value servo_quadrant
.
与此问题类似的问题涉及到函数外部的全局变量存在问题.在这种情况下,我认为这不是问题所在,因为仅从函数内部需要变量(尽管我可能是错的).
Questions similar to this one have involved there being an issue with a global variable outside of the function. I don't think that's the issue in this case, as the variable is only needed from within the function (although I could be wrong).
代码:
def servo_to_quadrant(servo_val):
if servo_val < 0: 360 + servo_val
if servo_val >= 360: servo_val = servo_val - 360
if servo_val >= 0 and servo_val < 90: servo_quadrant = 1
if servo_val >= 90 and servo_val < 180: servo_quadrant = 2
if servo_val >= 180 and servo_val < 270: servo_quadrant = 3
if servo_val >= 270 and servo_val < 360: servo_quadrant = 4
return servo_quadrant
servo_val = -30
quadrant = servo_to_quadrant(servo_val)
print(quadrant)
错误:
Traceback (most recent call last):
File "test2.py", line 11, in <module>
quadrant = servo_to_quadrant(servo_val)
File "test2.py", line 8, in servo_to_quadrant
return servo_quadrant
UnboundLocalError: local variable 'servo_quadrant' referenced before assignment
推荐答案
这是因为您在函数中的前面if
条件之一下分配了变量servo_quadrant
,并且如果没有条件返回True,则表示您将没有任何servo_quadrant
.为了解决这个问题,您需要在函数中初始化此变量.
It's because you have assigned the variable servo_quadrant
under one of the preceding if
conditions in your function, and if none of the conditions return True, you will haven't any servo_quadrant
. For getting ride of this problem you need to initial this variable in your function.
您可以将servo_quadrant = 0
放在函数的顶层,或者可以在返回任何内容之前检查servo_quadrant
的值:
You can put servo_quadrant = 0
on top level of your function or you can check the value of the servo_quadrant
before you return anything :
if servo_quadrant :
return servo_quadrant
return None
还注意,您需要重新分配变量servo_val
:
Also Note that you need to reassign variable servo_val
:
if servo_val < 0: servo_val=360 + servo_val
演示:
def servo_to_quadrant(servo_val):
servo_quadrant=0
if servo_val < 0: servo_val=360 + servo_val
if servo_val >= 360: servo_val = servo_val - 360
if servo_val >= 0 and servo_val < 90: servo_quadrant = 1
if servo_val >= 90 and servo_val < 180: servo_quadrant = 2
if servo_val >= 180 and servo_val < 270: servo_quadrant = 3
if servo_val >= 270 and servo_val < 360: servo_quadrant = 4
return servo_quadrant
servo_val = -30
quadrant = servo_to_quadrant(servo_val)
print quadrant
结果:
4
这篇关于UnBoundLocalError:赋值之前引用的局部变量(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!