Home > OS >  python - while loop structure
python - while loop structure

Time:09-20

I need help to construct a working while loop. my code goes like this

class Bot():
    def __init__(self):
        self.woke = False
        while self.woke == False:
            self.wake_word() # --> when it predicts wake word self.woke changes to True
            while self.woke == True:
                self.voice_recognition() # --> takes audio turns it to a spoke.txt file
                break
            self.chat() # --> reads the spoke.txt and finds a response
            self.respond() # --> speaks the responds using pyttsx3

the code works perfectly but only for one time..it does what I want it to do but for once and then the script stops. I need to run it until I give the command to stop it using

sys.exit(0) # in a function 

meaning when it responses it starts listening again (self.voice_recognition() function) and again does the chat() and finds a respond().

CodePudding user response:

Not exactly sure what you are looking for, but try this -

class Bot():
    def __init__(self):
        self.woke = False
        while self.woke == False:
            self.wake_word() # --> when it predicts wake word self.woke changes to True
            while self.woke == True:
                self.voice_recognition() # --> takes audio turns it to a spoke.txt file
                self.woke=False
                break
                

            self.chat() # --> reads the spoke.txt and finds a response
            self.respond() # --> speaks the responds using pyttsx3

CodePudding user response:

I had a problem with the way I'm capturing audio.. (I had to close the stream). what happened was that each time the voice_recognition() was called the stream was already open so the data didn't change and that causes an infinite loop inside the function which caused it to not work how it was supposed to

the final code the was correctly working is this

self.wake_word()
    while True:
        self.voice_recognition()
        self.chat()
        self.respond()

really simple and straight forward, the problem was with it the function not the while loop structure. Thanks for anyone who took the time and tried to answer I'm sure your answers / comments were correct as this wasn't about the while loop structure yet a simple unrecognized missing code.

  • Related