'Local Variable 'result' referenced before assignment

I am getting an UnboundLocalError. I don't know why, I was following a tutorial on YouTube on AI Chatbots (https://www.youtube.com/watch?v=1lwddP0KUEg), and the code was the same as his. His worked, mine didn't. Code:

def get_response(intents_list, intents_json):
    tag = intents_list[0]['intent']
    list_of_intents = intents_json['intents']
    for i in list_of_intents:
        if i['tag'] == tag:
            result = random.choice(i['responses'])
            break
    return result


print("GO!")

while True:
    message = input("")
    ints = predict_classes(message)
    res = get_response(ints, intents)
    print(res)


Solution 1:[1]

If list_of_intents is empty, or if there is no element in the list that satisfies the if condition - result will not be defined. Therefore, when you try to return result you get:

UnboundLocalError: local variable 'result' referenced before assignment

To solve this, you should define result before the for loop with a default value.

In addition, it sounds like the get_response function doesn't get the values you expect (i.e intents_list's and\or intents_json's content is different than what you are expecting). You can print their content to debug this.

In addition, it is better not to have the type of the object as part of its name. I would change list_of_intents to intents or maybe intents_contents.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1