Search code examples
pythonvariablesindentation

local variable referenced before assignment (CounterOne)


I ran the code before adding the CounterOne variable and it ran fine.

But after adding the CounterOne variable the compiler starts giving me below error.

"local variable 'CounterOne' referenced before assignment"

CounterOne = 0.00

def AAPILoad():
    return 0

def AAPIInit():
    return 0

def AAPIManage(time, timeSta, timeTrans, acycle):
    AKIPrintString( "AAPIManage" )      

    xy = doSomething() #Read Number of Sections
    for i in range (xy):
        id = getID(i) #Read the identifier of a section
        if (id==331):
            xyz = DoCal(id,True) #Read the number of vehicles in a section
            for j in range (xyz):
                Calculaitons

                if (0<=distanceFromTrafficLight<=300):
                    if ( condition == False) :
                        do calculations
                    else :
                        print ("Condition failed")

                    if ( Condition):  #Cruising 
                        Calval = 0.233+2*someValue

                        CounterOne = CounterOne + Calval
    return 0

Solution

  • CounterOne
    

    Is not a global variable, that is why the error is thrown.

    You can either make it global, which is not recommended, or pass the CounterOne value to the function.

    For global method:

    def AAPIManage(time, timeSta, timeTrans, acycle):
        global CounterOne
       AKIPrintString( "AAPIManage" )
    

    For function method :

    def AAPIManage(time, timeSta, timeTrans, acycle,CounterOne):
    

    AND RETURN CounterOne instead of zero