Python NameError: name 'result' is not defined

Viewed 33

I was making a simple chatbot ai Most of these codes are copied from others, so I don't know why the error is occurring.

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

I've tried deleting global, but then I get another error. And I tried to rename the variable, but it still makes an error. From what I searched, it seems to be a range-related problem, but I don't know how to solve it.

All I know is that there was an error in return result.

3 Answers

Not sure without seeing all the code, but it look like

  • global result has not been defined before calling the function
  • you assignment result = ... is inside an if, and your code never gets there

So, you probably return a variable that hasn't really been defined

Your problem is that result is never set, if the condition is not met (e.g. the json is empty). There are multiple ways to do this correctly. None of them will involve a global variable.

Set a default return value at the beginning:

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

Have an else statement after your for-loop

def get_response(intents_list, intents_json):
    tag = intents_list[0]['intents']
    list_of_intents = intents_json['intents']
    for i in list_of_intents:
        if i['tag'] == tag:
            result = random.choice(i['responses'])
            break
    else:
        result = None  # Default value to use, if for-loop was not broken
    return result

Simply return the values

def get_response(intents_list, intents_json):
    tag = intents_list[0]['intents']
    list_of_intents = intents_json['intents']
    for i in list_of_intents:
        if i['tag'] == tag:
            return random.choice(i['responses'])
    return None  # Return default value if nothing has been returned from inside the loop

Based on the code shared used you could try something as follows:

if i['tag'] == tag:
    return random.choice(i['responses'])
else:
    pass

Handle the else part as required. Setting the result to a global variable will return a previously set value even if the condition is not met.

Related