0

I am trying to compare a variable with two values not equal to but is not working

if 'Home' or 'Away' not in sku:
    print(sku)
    data = [sku, price]
else:
    print("Error")

2nd way

if sku!="Home" or sku!="Away":
    print(sku)
    data = [sku, price]
else:
    print("Error")

What I am missing here? Why it is passing nevertheless to data=[sku,price] in both cases?

  • What kind of variable is sku? – ngood97 Aug 04 '19 at 20:40
  • _if 'Home' or 'Away' not in sku:_ That is not the correct way to test for multiple values. See [this question](https://stackoverflow.com/q/15112125/494134). – John Gordon Aug 04 '19 at 20:40
  • It is something like X45XRT a product number –  Aug 04 '19 at 20:40
  • 2
    the first: `'Home' or 'Away' not in sku` converts to `('Home') or ('Away' not in sku)` Which is basically always True because non empty strings are truthy. – Paritosh Singh Aug 04 '19 at 20:41
  • 1
    _if sku!="Home" or sku!="Away":_ No matter what value `sku` has, this if statement will _always_ be true. If sku is "Home" then it doesn't equal "Away"; and if it's "Away" then it doesn't equal "Home". You should use `and` instead of `or`. – John Gordon Aug 04 '19 at 20:42
  • @Paritosh ok but why the 2nd way is not working?!?! –  Aug 04 '19 at 20:42
  • 2
    the second: `sku!="Home" or sku!="Away"` You've made a logical fallacy. `sku`, when equal to Home, is still going to give True for `sku!="Away"` . Read about de Morgan's law, and essentially, the point being, using `not` or `!=` or any negation gets messy, you have to use `and` here, cause the logic is flawed otherwise. – Paritosh Singh Aug 04 '19 at 20:42
  • 2
    Somehow every *single* day, this question is asked a few times. – Willem Van Onsem Aug 04 '19 at 20:43

1 Answers1

1

In the first way if 'Home' ... will always evaluate to True so you need some rearranging of your logic:

if not ('Home' in sku or 'Away' in sku):
    print(sku)
    data = [sku, price]
else:
    print("Error")

In the second way sku will never be both 'Home' and 'Away' which is how your logic currently reads, so this will always be True as well.

if sku!="Home" and sku!="Away":
    print(sku)
    data = [sku, price]
else:
    print("Error")
azundo
  • 5,902
  • 1
  • 14
  • 21
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer) note the section "Answer Well-Asked Questions", and the bullet point therein regarding questions which "have already been asked and answered many times before". – Charles Duffy Aug 04 '19 at 21:05