2

I am trying to only allow some input in python using the following code

while True:
    age=input('Are you 1,2 OR 3')
    if age== ('1' or '2' or '3'):
        break
    else:
        print('df')

When I enter 1, no error comes up and it continues to the rest of the programme, however when I enter 2 or 3, it comes up with the else: error. I've tried changing it round a bit and it seems as though it only accepts the first number from the choices (1). Probably a very simple fix. Thanks for any help.

JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
user3662438
  • 111
  • 2
  • 3
  • 6
  • I've closed as the dupe that I think you're ultimately asking for (type conversion and 2.x/3.x checking etc...)... but see http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values as to how to correctly test against multiple values in general – Jon Clements Mar 22 '15 at 23:12

2 Answers2

3

You need to change age checking with:

if age in ('1', '2', '3'):

'1' or '2' or '3' is a boolean expression that returns the first non empty string. And in this case the string is '1'.

For example:

>>> '1' or '2' or '3'
'1'
>>> '' or '2' or '3'
'2'
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
  • @aruisdante, `True` is not the chained `or` result as shown above. Also, from the syntax the OP is probably using Python 3, so `input` would be returning a string. – Mark Tolonen Mar 22 '15 at 23:17
  • Whoops, you're right, didn't think that one through all the way ;) Though nothing syntactically there screams 3, function-print is in 2.7. But yes, given that the chained `or` would in fact return `'1'`, almost certainly 3. – aruisdante Mar 22 '15 at 23:19
0

You cannot join comparisons like that. You can:

if age == '1' or age == '2' or age == '3':

or use the in operator as JuniorCompressor suggested.

Selcuk
  • 57,004
  • 12
  • 102
  • 110