python 引用局部变量_UnBoundLocalError:赋值之前引用的局部变量(Python)

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).

Code:

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)

Error:

Traceback (most recent call last):

File "test2.py", line 11, in

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

解决方案

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.

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

Also Note that you need to reassign variable servo_val :

if servo_val < 0: servo_val=360 + servo_val

Demo:

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

Result:

4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值