Python Forum
local varible referenced before assignment
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
local varible referenced before assignment
#1
I kept having this error: UnboundLocalError: local variable 'command' referenced before assignment

Does Anybody know how to solve it?

Here is the code:
import speech_recognition as sr
import pyttsx3 
import pywhatkit
import datetime
import wikipedia
import pyjokes
import random as rd


thx1 = ["Your Welcome", "No problem", "Its my job to help you"]

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

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

print("Im Ava what can i do for you?")
talk("Im Ava... what can i do for you?")
print("If you need any help say help")
talk("If you need any help say help")


def take_command():
    try:
        with sr.Microphone() as source:
            print("Listening...")
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            print(command)
            if 'ava' in command:
                command = command.replace('ava', '')
                
    except:
        pass
    return command

def run_ava():
    command = take_command()
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing' + song)
        pywhatkit.playonyt(song)

    elif 'help' in command:
        print("Here is what i can: play music on youtube, search something on wiki, tell jokes, tell time now")
        talk('Here is what i can')

    elif 'hear me' in command:
        print("Yes, I can hear you clear")
        talk("Yes, I can hear you clear")
    
    elif 'who are you' in command:
        print('Im Ava your virtual assistent')
        talk('Im Ava... your virtual assistent')

    elif 'how are you' in command:
        print("Im glad you asked. Im good thank you")
        talk("Im glad you asked. Im good thank you")

    elif 'thanks' in command:
        thx = rd.choice(thx1)
        print(thx)
        talk(thx)
    
    elif 'thank you' in command:
        thx = rd.choice(thx1)
        print(thx)
        talk(thx)

    elif 'male or female' in command:
        print('Male, Female, Nonbinary? Nah bro im a walmart bag')
        talk('male... female... nonbinary? nah broo.. im a walmart bag')

    elif 'time' in command:
        time = datetime.datetime.now().strftime('%H:%M')
        print(time)
        talk('Its' + time)
    elif 'tell me something about' in command:
        person = command.replace('tell me something about' , '')
        info = wikipedia.summary(person, 5)
        print(info)
        talk(info)
    elif 'who is' in command:
        person = command.replace('who is' , '')
        info = wikipedia.summary(person, 5)
        print(info)
        talk(info)
    elif 'what is' in command:
        person = command.replace('what is' , '')
        info = wikipedia.summary(person, 5)
        print(info)
        talk(info)
    elif 'joke' in command:
        joke = pyjokes.get_joke()
        print(joke)
        talk(joke)

    else:
        talk('Im not sure i understand')

        
while True:
    run_ava()
snippsat write Jan-10-2023, 05:22 PM:
Added code tag in your post,look at BBCode on how to use.
Reply
#2
Post entire error message including the stack trace.

If you had posted the error message I'm sure it would say the error was on line 40. An exception occurred listening to the microphone. No value was assigned to command. You try to return command at the end of the function.

An easy fix is assign a value to command in the exception body.
    except:
        # pass
        command = None
    return command
Reply
#3
It still didn't solve the problem There is another problem: the argument of type 'NoneType' is not iterable. Here is full error first:
Error:
File "d:\programy python\speakingchatbot.py", line 110, in <module> run_ava() File "d:\programy python\speakingchatbot.py", line 45, in run_ava command = take_command() File "d:\programy python\speakingchatbot.py", line 42, in take_command NameError: name 'command' is not defined
And the Second one:
Error:
Traceback (most recent call last): File "d:\programy python\speakingchatbot.py", line 109, in <module> run_ava() File "d:\programy python\speakingchatbot.py", line 45, in run_ava if 'play' in command: TypeError: argument of type 'NoneType' is not iterable
Yoriz write Jan-10-2023, 06:12 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#4
It solved the problem perfectly. Now you are getting further along and seeing another error in your program. Since it is possible that your function might return None, the code that uses the function return value will have to check for a None value. I suppose you could return an empty string instead of None, but returning None indicates an exception occurred when listening for a command. Your choice.
Reply
#5
If i leave empty string the chatbot is doing this over and over again:

else:
talk('Im not sure i understand')
Reply
#6
That means that this code is raising an exception:
        with sr.Microphone() as source:
            print("Listening...")
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            print(command)
            if 'ava' in command:
                command = command.replace('ava', '')
I suggest you remove the try/except that wraps this code and let Python tell you how it is failing.
Reply
#7
Just remove try/except in take_command() function.
Function should take argument in and not just get it magically from global namespace.
If i do quick test and take out Microphone as i have not set it up.
So i want it to tell a joke.
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import random as rd


thx1 = ["Your Welcome", "No problem", "Its my job to help you"]

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

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

print("Im Ava what can i do for you?")
talk("Im Ava... what can i do for you?")
print("If you need any help say help")
talk("If you need any help say help")

def take_command():
    '''
    with sr.Microphone() as source:
        print("Listening...")
        voice = listener.listen(source)
        command = listener.recognize_google(voice)
        command = command.lower()
        print(command)
        if 'ava' in command:
            command = command.replace('ava', '')
    '''
    return 'time'

def run_ava(take_command):
    command = take_command()
    if 'play99' in command:
        song = command.replace('play', '')
        talk('playing' + song)
        pywhatkit.playonyt(song)

    elif 'help' in command:
        print("Here is what i can: play music on youtube, search something on wiki, tell jokes, tell time now")
        talk('Here is what i can')

    elif 'hear me' in command:
        print("Yes, I can hear you clear")
        talk("Yes, I can hear you clear")

    elif 'who are you' in command:
        print('Im Ava your virtual assistent')
        talk('Im Ava... your virtual assistent')

    elif 'how are you' in command:
        print("Im glad you asked. Im good thank you")
        talk("Im glad you asked. Im good thank you")

    elif 'thanks' in command:
        thx = rd.choice(thx1)
        print(thx)
        talk(thx)

    elif 'thank you' in command:
        thx = rd.choice(thx1)
        print(thx)
        talk(thx)

    elif 'male or female' in command:
        print('Male, Female, Nonbinary? Nah bro im a walmart bag')
        talk('male... female... nonbinary? nah broo.. im a walmart bag')

    elif 'time' in command:
        time = datetime.datetime.now().strftime('%H:%M')
        print(time)
        talk('Its' + time)
    elif 'tell me something about' in command:
        person = command.replace('tell me something about' , '')
        info = wikipedia.summary(person, 5)
        print(info)
        talk(info)
    elif 'who is' in command:
        person = command.replace('who is' , '')
        info = wikipedia.summary(person, 5)
        print(info)
        talk(info)
    elif 'what is' in command:
        person = command.replace('what is' , '')
        info = wikipedia.summary(person, 5)
        print(info)
        talk(info)
    elif 'joke' in command:
        joke = pyjokes.get_joke()
        print(joke)
        talk(joke)

    else:
        talk('Im not sure i understand')

run_ava(take_command)
Output:
(dl_env) G:\div_code\dl_env λ python speak.py Im Ava what can i do for you? If you need any help say help If you play a Windows CD backwards, you'll hear satanic chanting ... worse still, if you play it forwards, it installs Windows.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  UnboundLocalError: local variable 'wmi' referenced before assignment ilknurg 2 1,923 Feb-10-2022, 07:36 PM
Last Post: deanhystad
  Python 3.8 Nested varible not updating Teknohead23 6 2,447 Oct-02-2021, 11:49 AM
Last Post: Teknohead23
  Referenced before assignment finndude 3 3,288 Mar-02-2021, 08:11 PM
Last Post: finndude
  ReferenceError: weakly-referenced object no longer exists MrBitPythoner 17 11,575 Dec-14-2020, 07:34 PM
Last Post: buran
  UnboundLocalError: local variable 'figure_perso' referenced before assignment mederic39 2 2,282 Jun-11-2020, 12:45 PM
Last Post: Yoriz
  local variable 'marks' referenced before assignment Calli 3 2,341 May-25-2020, 03:15 PM
Last Post: Calli
  UnboundLocalError: local variable referenced before assignment svr 1 3,322 Dec-27-2019, 09:08 AM
Last Post: perfringo
  UnboundLocalError: local variable ' ' referenced before assignment d3fi 10 5,592 Sep-03-2019, 07:22 PM
Last Post: buran
  local variable referenced before assignment. samvup 3 4,625 Aug-26-2019, 07:07 PM
Last Post: buran
  local variable 'option' referenced before assignment RedSkeleton007 11 7,973 Feb-23-2018, 07:16 AM
Last Post: RedSkeleton007

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020