OR operator breaks the if..elif..else block in python

Question:

I am new to python, I have been trying to use the text to speech module it works fine but when I try to add an OR operator to my if..elif..else block the program discards everything below the elif statement that contains the OR operator, any help will be greatly appreciated. Code provided below

def response(text):
   if text != "":
        if 'hello jarvis' in text:
            print("hello sir, how can i help you")
            speak("hello sir, how can i help you")
        
        elif 'how are you' in text:
            print("I'm fine sir, how are you?")
            speak("I'm fine sir, how are you?")

        elif 'are you alive' in text:
            print("no i am not alive, i am just a combination of very complex algorithms that keeps me functional")
            speak("no i am not alive, i am just a combination of very complex algorithms that keeps me functional")
            

        elif 'what is the time' or 'what time is it' in text:
            strtime = datetime.today().strftime("%H:%M:%p")
            print(f"the time is {strtime}")
            speak(f"the time is {strtime}")

        elif 'thank you' in text:
            speak("you are welcome sir")
            exit()

        else:
            url = f"https://www.google.com/search?q={text}"
            webbrowser.get().open(url)
            speak("here is what i found")

   else:
     speak("call me when you have something to ask me")

Asked By: Mundheer Suleiman

||

Answers:

The issue is that 'what is the time' per se is regarded as True, thus the branch is always taken. Simply change

elif 'what is the time' or 'what time is it' in text:

to

elif 'what is the time' in text or 'what time is it' in text:
Answered By: Michael Hodel

Try this:

elif 'what is the time' in text or 'what time is it' in text:
            strtime = datetime.today().strftime("%H:%M:%p")
            print(f"the time is {strtime}")
            speak(f"the time is {strtime}")

The reason for this is because in your original code you’re seeing if ('what is the time') evaluates to true and then if ('what time is it' in text) evaluates to true, you aren’t comparing them together. The first comparison doesn’t make sense because strings can’t evaluate to boolean values.

Answered By: BVB44
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.