0

I am making an impossibly simple piece of code to check for words in a string of inputted text but the IN is returning true when it obviously should return false and I've tested different versions of the code for a few hours and cant reason why this happens?!?

    >>> y= "yeh im gonna lose my mind over this"
    >>> if "screen" or "display" or "crack" or "smash" in y:
    ...     print ("Y does this happen?")
    ... 
    Y does this happen? #Output

EDIT: I think this question is viable and not a duplicate as it entails the information of the ordering of the IN and OR statement in a loop whereas the previous question i believe only asked for a simple answer on IN statements.

  • [Operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence) is well defined in Python. There is no dark magic here, only simple _obvious_ rules applied. – Łukasz Rogalski Jun 02 '16 at 14:22
  • yes i know, but almost all of physics was once considered magic until we came up with some thoeries! :) – PythonGuy_InNeed Jun 02 '16 at 14:51
  • @PythonGuy_InNeed FWIW I chose that question because it's our standard target for lots of questions where people not used to Python make this mistake with `or`, not because your question is literally identical. Also, I definitely recommend looking at things like `any` or something shorter than the very repetitive answer you've chosen. Imagine doing that for a list of 12 items! – Two-Bit Alchemist Jun 02 '16 at 15:01
  • @Two-Bit Alchemist Yes i do thank you for your help and will experiment with the "any" statement – PythonGuy_InNeed Jun 03 '16 at 16:41

3 Answers3

1

You are probably not using in as you intended:

if "screen" in y or "display" in y or "crack" in y or "smash" in y

What you've done will always return True because the truthy value of a non empty string is True

So if "screen" returns True and no matter what the others are, the if always evaluates to True

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

You probably want an any test here:

In [1]: y = "yeah I'm gonna lose my mind over this"

In [2]: if any(word in y for word in ('screen', 'display', 'crack', 'smash')):
   ...:     print('why does this happen?')
   ...: else:
   ...:     print("it doesn't ;)")
   ...:
it doesn't ;)

In [3]: if any(word in y for word in ('yeah', 'screen', 'display', 'crack', 'smash')):
   ...:     print('now it happens')
   ...:
now it happens
Two-Bit Alchemist
  • 17,966
  • 6
  • 47
  • 82
0

or is lasily evaluated and has lower priority than in statement, which means your statement

if "screen" or "display" or "crack" or "smash" in y

evaluates to

if "screen" or ("display" or ("crack" or ("smash" in y)))

As "screen" is a true value, or "returns True" and the remaining of the condition is never evaluated.

Diane M
  • 1,503
  • 1
  • 12
  • 23