1

I'm trying to check if "i" is not equal to "test" or "test2". If I set "i" to str("test") or str("test2) then it will say "i is not test or test2", and if I set "i" to something else like str("x") it functions normally.

    if str(i) != str("test") or str("test2"):
      print ("i is not test or test2")
    else:
      print ("i is test or test2")
Zeinab Abbasimazar
  • 9,835
  • 23
  • 82
  • 131
TRSI
  • 117
  • 1
  • 1
  • 7

2 Answers2

3

The or statement doesn't works like that, or operator requires boolean as the two operands, but in your case, the or is applied to a boolnea and str operator. The Python doesn't raises exception in this case, and internally converts the str to True value and processes the or operand.

Now you have two options, either you rectify your if statement as:

if str(i) != str("test") or str(i) !=str("test2"):
    print ("i is neither test not test2")

Or you may use:

if str(i) not in {str("test"), str("test2")}:
    print ("i is neither test not test2")
ZdaR
  • 22,343
  • 7
  • 66
  • 87
0

try:

if str(i) != "test" and str(i) != "test2":
      print ("i is not test or test2")
    else:
      print ("i is test or test2")
Maged Saeed
  • 1,784
  • 2
  • 16
  • 35
  • This post looks more like a comment than ans answer. Answer can't be a simple "try this", should be elaborate and explaining why doesn't works. If you are so lazy to do it, like me, just post a comment. Also, be accurate, where it says `"i is not test or test2"` should be `"i is not test neither test2"`. – dani herrera Sep 16 '17 at 08:10
  • You need `and` here -- logic doesn't work the same way English does. – Gordon Davisson Sep 16 '17 at 08:12
  • Thanks for your comment Mr @danihp, I was about to explain, but there is another answer better explaining what I was thinking of. I already gave it a thump up. – Maged Saeed Sep 16 '17 at 08:12
  • that is great Mr @GordonDavisson, I am editing it right now. – Maged Saeed Sep 16 '17 at 08:13
  • I just expained in a previous comment. ^_^ – Maged Saeed Sep 16 '17 at 11:26