So I have been learning python lately, and I found a tutorial on how to make an artificial assistant. I have some basic/intermediate knowledge about python but I can't figure out the errors I am getting. They appeared after I added the while loop. I am also new to this platform so forgive me if I made any mistakes and thank you already.
Here is the code:
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
rate = engine.getProperty('rate')
engine.setProperty('rate', rate-35)
engine.setProperty('voice', voices[2].id)
def speak(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
print('I\'m Listening')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'jarvis' in command:
command = command.replace('jarvis', '')
print('I heard ' + '\"'+command+' \"')
except:
pass
return command
def run_jarvis():
command = take_command()
if 'play' in command:
song = command.replace('play', '')
speak('Playing' + song)
pywhatkit.playonyt(song)
print('Playing' + song)
elif "what time is it" in command:
time = datetime.datetime.now().strftime('%H:%M')
speak('It is' + time)
print(time)
elif 'who is' in command:
person = command.replace('who is', '')
info = wikipedia.summary(person, 1)
print(info)
pywhatkit.search(person)
speak(info)
elif 'search' in command:
question = command.replace('search', '')
pywhatkit.search(question)
else:
speak('Sorry, I couldn\'t understand.')
speak('Can you repeat?')
print('Sorry, I couldn\'t understand.')
while True:
run_jarvis()
And here is the error I am getting:
Traceback (most recent call last):
File "C:/Users/CAN/PycharmProjects/Jarvis 0.1/jarvis.py", line 67, in run_jarvis()
File "C:/Users/CAN/PycharmProjects/Jarvis 0.1/jarvis.py", line 37, in run_jarvis command = take_command()
File "C:/Users/CAN/PycharmProjects/Jarvis 0.1/jarvis.py", line 33, in take_command return command
UnboundLocalError: local variable 'command' referenced before assignment
Process finished with exit code 1
commandwhen you're erroring before it is assigned. Either fix the error, or add acommand = Nonebefore yourtry.except: passis also terrible practice! Consider making it at leastException(otherwise it will catch^Cet al.) and a more complex solution with feedback likeexcept Exception as ex: print("caught Exception: {}".format(repr(ex))"I can't figure out the errors I am getting"- well, you swallow the important details of your actual errors with yourexcept: pass. But, yeah, what @thethiny said, you're accessingcommandwhich may not be initialized if you run into an exception.