1

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

5
  • 4
    you're returning command when you're erroring before it is assigned. Either fix the error, or add a command = None before your try. Commented Apr 7, 2021 at 20:46
  • 2
    Simply except: pass is also terrible practice! Consider making it at least Exception (otherwise it will catch ^C et al.) and a more complex solution with feedback like except Exception as ex: print("caught Exception: {}".format(repr(ex)) Commented Apr 7, 2021 at 20:48
  • 2
    "I can't figure out the errors I am getting" - well, you swallow the important details of your actual errors with your except: pass. But, yeah, what @thethiny said, you're accessing command which may not be initialized if you run into an exception. Commented Apr 7, 2021 at 20:48
  • You are returning NoneType in this function. You cannot iterate through nothing, if this error was not raised, something itterable would be returned. In your case an error was raised and NoneType was returned which is impossible to iterate through. So you need to figure out why this error is being raised. Commented Apr 7, 2021 at 21:39
  • Dont pass on the except, print it, and re-post details of the error. Commented Apr 8, 2021 at 1:39

2 Answers 2

1

In every modern programming language that I know you must declare the variable before you can use it. In JavaScript, for example, you must write var x; and then you can use the name x for the variable. But Python doesn't know the command for declaration (you can't just write x), but you must assign it. If you don't know the value and you want just to say the interpreter that this variable exists, you can write x = None.

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

5 Comments

x = None is creating a variable and assigning it, not declaring the variable.
Yes, but I don't know the way to only declare the variable in Python. You can't just write x. See the section Creating variables: w3schools.com/python/python_variables.asp.
"Python has no command for declaring a variable." it says right at the top. I think you are confused about what it means to declare a variable.
Yes, I linked the W3schools page, section Creating variable: "Python has no command for declaring a variable. A variable is created the moment you first assign a value to it." I don't think I am confused here. Otherwise, I edited my question to be even more clear. Is there still anything wrong?
To absolutely labor the point, but with a positive spin, this is a delightful read and discusses some of the why david.goodger.org/projects/pycon/2007/idiomatic/handout.html (it's old and some exact logic is no longer true, but the history is very valuable)
1

There error seems to be here.

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

This is occurring because command is not defined. An error occurs in your try section before command is defined. So then it excepts in and tries to return command. Though like I said above command is not defined. So where you except:pass instead of pass make it return None

Update: someone in the comment suggested putting the return command in the try block which makes more sense.

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+' \"')
            return command
    except:
        return None
    

How to check what error is being raised.

    except Exception as e:
        print(e)

7 Comments

What do you mean?
sorry, I meant change "Command" to command for readability, directly under the first code.
You should return the command from within the try/except block and return None outside of the try/except block. The command outside of the try/except is not in scope since it is only be initialized within the try/except block.
Are you saying return command in the try block?
@BuddyBobIII thank you for your kind answers. Even though I did everything you and others said I couldn't fix the problem. I am still getting the same 'NoneType' error. So I decided to take a new approach to this since I couldn't fix it. I will research more and watch more tutorials to get this right. If I could find a solution I'll come back here and edit the right code. Thank you all for helping me!
|

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.