Search code examples
pythonpyttsx3

How to make a part of a code go in loop without duplicate the code in Python


I'm using pyttsx3 to make a talking bot . and it work

import pyttsx3
f = pyttsx3.init()

a = input("type something: ")

if a == "hello":
    print(f.say("Hi How are you"))

f.runAndWait()

but if I want the code to repeat the operation when ever its end I mean if I typed something and got the respond I will get another "type something" input without duplicate the code like this

import pyttsx3
f = pyttsx3.init()

a = input("type something: ")

if a == "hello":
    print(f.say("Hi How are you"))
f.runAndWait()

b = input("type something: ")

if b == "hi":
    print(f.say("Hi"))
f.runAndWait()
c = input("type something: ")

if c == "hey":
    print(f.say("hi hows going"))

f.runAndWait()

i tried making a loop but didn't work

import pyttsx3
f = pyttsx3.init()

a = input("type something: ")

if a == "hello":
    print(f.say("Hi How are you"))

for a in f:
    print(a)

f.runAndWait()

So its going to ask me the a input again and again with no need to duplicate the code


Solution

  • I think it should work, I really didn't understand your question, but this is closest to what you asked for

    import pyttsx3
    f = pyttsx3.init()
    while True:
        a = input("type something: ")
        if a == "hello":
            print(f.say("Hi how are you?"))
        elif a == "hi":
            print(f.say("Hi"))
        elif a == "hey":
            print(f.say("hi hows going"))
        f.runAndWait()
    

    or if you want to try functions you can try:

    import pyttsx3
    f = pyttsx3.init()
    while True:
        nameoffunction()
    
    def nameoffunction():
        a = input("type something: ")
        if a == "hello":
            print(f.say("Hi how are you?"))
        elif a == "hi":
            print(f.say("Hi"))
        elif a == "hey":
            print(f.say("hi hows going"))
        f.runAndWait()