-2
def chat():
    print("Start talking with the bot (type quit to stop)!")
    while True:
        inp = input("You: ")
        if inp.lower() == "quit":
            break

        results = model.predict([bag_of_words(inp, words)])[0]
        results_index = numpy.argmax(results)
        tag = labels[results_index]
      

        if results[results_index] > 0.7: 
            for tg in data["intents"]:
                if tg['tag'] == tag:
                    responses = tg['responses']
            
            print(random.choice(responses))
        else:
            print("I couldn't get what u meant.")
chat()

https://docs.google.com/document/d/1UF-NQqg3SbUWdUoh-a3iBXcD1JsWg7y3/edit?usp=sharing&ouid=102983311954188847696&rtpof=true&sd=true

UnboundLocalError: local variable 'responses' referenced before assignment

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Please attach the code so that the question can be more clear – Sidharth Mudgil Jun 29 '22 at 11:28
  • 1
    What if `data['intents']` is empty or the `if` condition is never true…? – deceze Jun 29 '22 at 11:33
  • The `responses` variable is only defined if *two* previous if statements validate to `True`. Therefore, the second if statement is not validating, so the required variable is not being set. Or, `data` is empty. – S3DEV Jun 29 '22 at 11:33

2 Answers2

0

You declare the responses variable in an if statement. So if the code execution doesn't enter this scope, this variable will not be assigned. That's why you get an error.

To fix this, assign some 'empty' value to this variable before the if.

Meeso
  • 36
  • 4
0

You have to first declare the responses outside the if statement so that the scope of it will be in the while loop

responses = []
if results[results_index] > 0.7: 
     for tg in data["intents"]:
          if tg['tag'] == tag:
               responses = tg['responses']
Sidharth Mudgil
  • 1,293
  • 8
  • 25