2

I keep getting: NameError: name 'statement' is not defined. It's because i'm not saying anything, and I tried to do an "except" to catch the errors and print something but it still does the error. Here is the code:

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say Anything: ")
        audio = r.listen(source)
        try:
            statement = r.recognize_google(audio).lower()
            print("You said : {}".format(statement))
        except sr.UnknownValueError:
            print(random.choice(command_errors))
        except NameError:
            print(random.choice(command_errors))
        if ai_name in statement:
            engine.say("At your service")
            response_to_wake = ("At your service, " + user_pronoun.lower())
            engine.runAndWait()
            print(response_to_wake)
            Wake = True
        else:
            Wake = False
1
  • you could as start create statement = None to have this variable all time. And later you can use if statement is not None: to recognize if recognize_google could recognize speech. OR you should create statement = '' inside except to create this varaible when recognize_google will raise error. Commented Dec 14, 2020 at 23:29

1 Answer 1

1

If recognize_google throws, then statement will not be defined after the try-except block. Consider moving the if ai_name in statement block inside the try block or initialize statement before it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.