0

Working through EDX python course. Not sure why when I use '!=' with 'or' statement code doesn't work as expected.

But I use '==' it does work.

x = input("Enter a letter: ")
if x == 'h' or x =='l' or x =='c':
    print('Correct letter')
else:
    print('Wrong letter')

x = input("Enter a letter: ")
if x != 'h' or x !='l' or x !='c':
    print('Wrong letter')    
else:
    print('Correct letter')

in the x variable example: entering 'h','l','c' prints 'correct letter' anything else prints 'wrong letter'

in the y variable example: entering 'h','l','c' prints 'wrong letter' all the time

bbhbottle
  • 3
  • 2
  • Where's the y variable? – Eric Sep 11 '19 at 18:11
  • 3
    Possible duplicate of [Why non-equality check of one variable against many values always returns true?](https://stackoverflow.com/questions/26337003/why-non-equality-check-of-one-variable-against-many-values-always-returns-true) – melpomene Sep 11 '19 at 18:12
  • Also, https://stackoverflow.com/questions/36605454/why-is-my-c-o-c-x-condition-always-true. – melpomene Sep 11 '19 at 18:14
  • That's the correct logic. Entering 'h' will fail the first criteria, but will satisfy the second criteria, so it will return 'Wrong letter'. – Eric Sep 11 '19 at 18:14
  • @bbhbottle If for an `if` condition, even if one of the `or` clause is evaluated as `True` which is equal to `1`, the whole `if` clause has a cumulative result as `True` even though others may fail. When you have a possible set of values, better use `in`, and all the possible values in form of a list. And I think your second variable should be `y`. – a_r Sep 11 '19 at 18:41

2 Answers2

1

Because of basic logic. If x == 'h' then it will automatically be x != 'l' and will be x != 'c', which mean that when you substitute it with logical values it ends as false or true or true which is naturally true. Negation of alternative is conjunction of negations by de Morgan's Laws.

Hauleth
  • 22,873
  • 4
  • 61
  • 112
0

Changing the OR with AND should solve your problem. You need all condition to be satisfied

x = input("Enter a letter: ")
if x != 'h' and x !='l' and x !='c':
    print('Wrong letter')    
else:
    print('Correct letter')
Eric
  • 3,165
  • 1
  • 19
  • 25