Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UnboundLocalError: cannot access local variable 'command' where it is not associated with a value #141

Open
AtharvShinde2004 opened this issue Oct 22, 2023 · 1 comment

Comments

@AtharvShinde2004
Copy link

The error you're encountering, "UnboundLocalError: cannot access local variable 'command' where it is not associated with a value," is occurring because the variable command is defined within the try block in the take_command function, and there's a possibility that it may not be assigned a value if an exception occurs. In Python, you cannot access a variable before it's assigned a value, and this error is raised when you try to do so.

To fix this issue, you can initialize the command variable with an empty string before the try block, like this:

def take_command():
    command = ""  # Initialize command with an empty string
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexa' in command:
                command = command.replace('alexa', '')
                print(command)
    except:
        pass
    return command

This way, even if an exception occurs, the command variable will still have a value (an empty string), and you won't encounter the UnboundLocalError.

@lalitabehura
Copy link

I added the command="" a empty string in order to fix the UnboundLocalError, but It is keep repeating " Please say the command again " ,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants