0
    test = ''

# This loop infinitely

    while test != 'O' or test != 'X':
        test = raw_input("Enter: ").upper()

# This works fine   

    while not(test == 'O' or test == 'X'):
        test = raw_input("Enter: ").upper()

What's the difference between putting not and using != ?

Garren S
  • 5,552
  • 3
  • 30
  • 45
Jay
  • 11
  • 1
  • 1
    Possible duplicate of [Python != operation vs "is not"](http://stackoverflow.com/questions/2209755/python-operation-vs-is-not) – quantik May 19 '17 at 21:26
  • 1
    I would not consider that a duplicate. There is no use of `is` here. – Kenneth K. May 19 '17 at 21:26
  • Then it's a duplicate of this http://stackoverflow.com/questions/31026754/python-if-not-vs-if/31026976 @KennethK. – quantik May 19 '17 at 21:28
  • 1
    Erm, I'd still say not. The big issue here is DeMorgan's, as identified by the answer below. Your proposal does not have a compound condition. – Kenneth K. May 19 '17 at 21:30
  • 1
    @quantik: Also not a duplicate. The first question hinges on the `is` operator. The second asks for efficiency between the two, whereas the current question has a functionality problem. – Prune May 19 '17 at 21:31
  • OP, you want to know about "De Morgan's law". – T Tse Mar 14 '18 at 18:04

2 Answers2

17

The problem is your conjunction: you failed to apply DeMorgan's laws properly. You need to flip from or to and when you distribute the negation.

not(test == 'O' or test == 'X')

is equivalent to

test!= 'O' and test!= 'X'

Look at the logic of test!= 'O' or test!= 'X': no matter what character you give to test, it will be not equal to at least one of the two test characters. F0r O, the second clause is True; for X, the first is True; for any other character, both clauses are True. To get past this, you'd need a character that was X and O at the same time.

We're not doing quantum variables in Python ... not yet, at least. You'd have to write a new class with custom equality operators to make this work.

Prune
  • 76,765
  • 14
  • 60
  • 81
2

... and if you go Pythonic all the way, you will write

while not test in ('O', 'X'):

or - even simpler

while not test in 'OX':
volcano
  • 3,578
  • 21
  • 28
  • Yes, `not in` is better not only because of the Pythonicness, but also because this way you don't have to worry about precedence. – T Tse Mar 14 '18 at 18:03