-4

I want to print out a message if user input is != 0 or 1.

entering = int(input('enter 0 or 1: '))

I can get it to work for either 0 or 1, but when I try to combine both in one if-condition, it doesn't work. Following 2 options I tried:

if entering != 0 or entering != 1:
    print('invalid input')

if entering != 0 or 1:
    print('invalid input')

If I then enter 0 or 1, it still prints 'invalid input'. What am I missing?

pythonbrutus
  • 131
  • 3
  • 9
  • just curious, why do people sometimes downgrade normal questions? did I do anything wrong in the way I asked this question? – pythonbrutus Jan 01 '17 at 21:57
  • It's called a "downvote" and you got some because this question is exceedingly basic, and could have been answered by simply reading your textbook. It is not clear that you performed any research before posting. – Lightness Races in Orbit Jan 01 '17 at 21:59

3 Answers3

2

You want to exclude values of 0 and 1, so the condition must be an and expression, not an or expression.

if entering != 0 and entering != 1:
    print('invalid input')
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
1

In the first case, one of the conditions is guaranteed to be true: if entering ==0, then entering != 1 and vice versa. In the second case, it is evaluated as (entering != 0) or 1, and 1 is always true.

You want and:

if entering != 0 and entering != 1:

or the not in operator:

if entering not in [0,1]:
dawg
  • 98,345
  • 23
  • 131
  • 206
chepner
  • 497,756
  • 71
  • 530
  • 681
0

I would rewrite as:

while True:
    entry=input('enter 0 or 1: ') #raw_input if Python 2
    if entry in ('0','1'):
        user_input=int(entry)
        break
    else:
        print 'Invalid Entry'   
dawg
  • 98,345
  • 23
  • 131
  • 206