Skip to content Skip to sidebar Skip to footer

Unboundlocalerror: Local Variable Referenced Before Assignment (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 out

Solution 1:

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 :

ifservo_val<0:servo_val=360+servo_val

Demo:

defservo_to_quadrant(servo_val):servo_quadrant=0ifservo_val<0:servo_val=360+servo_valifservo_val>=360:servo_val=servo_val-360ifservo_val>=0andservo_val<90:servo_quadrant=1ifservo_val>=90andservo_val<180:servo_quadrant=2ifservo_val>=180andservo_val<270:servo_quadrant=3ifservo_val>=270andservo_val<360:servo_quadrant=4returnservo_quadrantservo_val=-30quadrant=servo_to_quadrant(servo_val)printquadrant

Result:

4

Solution 2:

This is because you try to modify servo_quadrant which isn't defined in your function. Python uses global scope by default if you just read a variable. So if you don't modify it everything will work fine. If you need to modify it just add global servo_quadrant at the beginning of your function.

Solution 3:

You need to make sure you assign servo_quadrant in every path through your function before you try and return it.

defservo_to_quadrant(servo_val):ifservo_val<0:360+servo_val# <--- This does nothingifservo_val>=360:servo_val=servo_val-360# <--- This assumes servo_val < 720ifservo_val>=0andservo_val<90:servo_quadrant=1ifservo_val>=90andservo_val<180:servo_quadrant=2ifservo_val>=180andservo_val<270:servo_quadrant=3ifservo_val>=270andservo_val<360:servo_quadrant=4# At this point, servo_quadrant may still not have been assignedreturnservo_quadrant

If you want to move servo_val into the range 0<=servo_val<360, you can use the modulo operator. And you can take advantage of the fact that if you return from a function, you don't need to keep checking the same conditions.

def servo_to_quadrant(servo_val):
    servo_val %= 360if servo_val < 90: return1if servo_val < 180: return2if servo_val < 270: return3return4

Post a Comment for "Unboundlocalerror: Local Variable Referenced Before Assignment (python)"