1

So I am trying to code this thing that lets you open pages on the web. I am using def functions to define the code and stating those in a while True loop. This is my code:

import webbrowser
cd = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"

#opening web pages
def yt():
    print ('Opening...')
    webbrowser.get(cd).open('youtube.com')

#loop code
while True:
    query = input()
    if 'open yt' or 'open youtube' in query:
        yt()
    else:
        break

So here when I take the input as 'open yt' or 'open youtube', it opens the desired web page but when the input is something else, instead of breaking the loop and ending the code, it opens YouTube again. I am not able to understand what is happening as I am a bit new to this kind of code. Please help.

FulStop
  • 11
  • 1
  • 1
    tl;dr: `if 'open yt' in query or 'open youtube' in query:`. – AKX Jan 12 '22 at 06:15
  • From the linked question, yours is a similar issue: you need `if 'open yt' in query or 'open youtube' in query:`. Otherwise `'open yt'` is subjected to truth test first and since it is a nonempty string, it evaluates to True and `or` [short-circuits](https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting) so you get True overall in the boolean context of if. Therefore that else is never reached. – Mustafa Aydın Jan 12 '22 at 06:17
  • What that if statement is doing is `if ('open yt') or ('open youtube' in query)`. It starts off checking the boolean value of the string `'open yt'` which returns True and then runs the function. – Josh Ackland Jan 12 '22 at 06:17

1 Answers1

-1

Issue is in if condition.

Try:

#loop code
while True:
    query = input()
    if 'open yt' in query or 'open youtube' in query:
        yt()
    else:
        break

Explanation:

>>> if "harsha":
...   print("hi")
...
hi
>>> if "":
...   print("hi")
...
<<No output>>

The condition in string will always be true as it checks string is non empty.

Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61