-2

In the code below, the if statement is triggering no matter the condition satisfies or not. the problem is with 'or' or anything else i do not know. please help

while True:
q = input("WRITE:")
if 'a' or 'b' in q:
    print("yes")
else:
    print("no")

I saw some fix about it like applying parenthesis i.e

while True:
q = input("WRITE:")
if('a') or ('b') in q:
    print("yes")
else:
    print("no")

but this is also triggering no matter the condition satisfies or not.

I also tried this

while True:
q = input("WRITE:")
if('a' or 'b') in q:
    print("yes")
else:
    print("no")

but this also did not work please help me. how to fix it

  • 1
    This is parsed the same as `if ('a') or ('b' in q)`; `in` does not "distribute" over `'a' or 'b'`. – chepner Jun 09 '20 at 15:53

1 Answers1

2

You need to use it like this:

if 'a' in q or 'b' in q:
    ...

It is necessary to check for every variable if it is in q.

Clause under if:

if 'a':

will always be executed, because it is "truthy". Python considers string "truthy" if it is not an empty string.

"falsy" are empty strings, 0 integer, empty arrays and empty dicts.

Pavel Botsman
  • 773
  • 1
  • 11
  • 25
  • 3
    There's also `if any(x in q for x in ['a', 'b']):`, but that's overkill for just two options. – chepner Jun 09 '20 at 15:53
  • @chepner literally I was going to paste `if any( x in ['a', 'b'] for x in q):` as answer and I saw your comment, that stopped me. – Zain Arshad Jun 09 '20 at 15:56