简体   繁体   中英

Getting the below error: please help: UnboundLocalError: local variable 'command' referenced before assignment

I am getting the below error while compiling a code in python. How Can I get rid of this error. Please Help

Error message:

    Traceback (most recent call last):
  File "C:\Users\Sohini\PycharmProjects\myownvirtualassistant\original code.py", line 70, in <module>
    run_alexa()
  File "C:\Users\Sohini\PycharmProjects\myownvirtualassistant\original code.py", line 43, in run_alexa
    command = take_command()
  File "C:\Users\Sohini\PycharmProjects\myownvirtualassistant\original code.py", line 37, in take_command
    return command

The original Code:

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)




def talk(text):
    engine.say(text)
    engine.runAndWait()




def take_command():
    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




def run_alexa():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        talk('Current time is ' + time)
    elif 'who the heck is' in command:
        person = command.replace('who the heck is', '')
        info = wikipedia.summary(person, 1)
        print(info)
        talk(info)
    elif 'date' in command:
        talk('sorry, I have a headache')
    elif 'are you single' in command:
        talk('I am in a relationship with wifi')
    elif 'joke' in command:
        talk(pyjokes.get_joke())
    else:
        talk('Please say the command again.')




while True:
    run_alexa()

UnboundLocalError: local variable 'command' referenced before assignment"

I am getting the below error while compiling a code in python. How Can I get rid of this error. Please Help

This a code to create a VA in Python.

When assinging command=take_command() it should be command=take_command

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM