Search code examples
pythonpython-3.xvariableslocal-variables

Python local variable 'message' referenced before assignment problem


liquid = [l_press,l_dosage,l_bottle,l_position,l_clog,l_counter]
for j in range(len(liquid)):
        data = liquid_filling(liquid[j])
        publish.single(liquid[j],data,qos = 0, hostname = hostname,port=2259)

def liquid_filling(topic):
    if topic == "Liquid_filling/pressure":
        message = random.uniform(4.0,5.0)
    elif topic == "Liquid_filling/dosage":
        message = random.uniform(495.0,505.0)
    elif topic == "Liquid_filling/bottle_presence" or topic== "Liquid_filling/position" or topic=="Caps/position":
        if i % 2 == 0:
           message = 'YES'
        else:
           message = 'NO'
    elif topic == "Liquid_filling/counter":
        message = i
    return message

I receive the following error:

Error: local variable 'message' referenced before assignment

I think that it must be something related with the alignment of the code but I have double-check it and I can't find any problem. Also, the variable message is only used to return a value.

I have already checked other related questions in this forum and I still cannot find the answer.

I would appreciate your help.


Solution

  • I solved it. It was that I had a topic named "Caps/position" and it should be named "Liquid_filling/position".

    The code that works is as follows:

    def liquid_filling(topic):
        if topic == "Liquid_filling/pressure":
            message = random.uniform(4.0,5.0)
        elif topic == "Liquid_filling/dosage":
            message = random.uniform(495.0,505.0)
        elif topic == "Liquid_filling/bottle_presence" or topic== "Liquid_filling/position" or topic=="Liquid_filling/anti_clogging":
            if i % 2 == 0:
               message = 'YES'
            else:
               message = 'NO'
        elif topic == "Liquid_filling/counter":
            message = i
        else: 
            message = 'There is an error'
        return message
    

    Thanks for your comments because I was able to realize the problem!