3

What's the best way to simplify this if?

#!/usr/bin/python

ans=input("choose yes or no: ")

if ans == "yes" or ans == "YES" or ans == "y" or ans == "Y":
    print("ok")
else:
        print("no")
Anton Protopopov
  • 27,206
  • 10
  • 83
  • 90
Pol Hallen
  • 1,824
  • 6
  • 29
  • 43
  • 2
    Do you want yEs or yeS? If so, check [.lower()](https://docs.python.org/2/library/stdtypes.html#str.lower) aswell. – Lafexlos Dec 31 '15 at 13:36

4 Answers4

9

You could check it with list:

if ans in ['yes', 'YES', 'y', 'Y']:
    print('ok')
else:
    print('no')
Anton Protopopov
  • 27,206
  • 10
  • 83
  • 90
4

I would recommend streamlining it as follows:

if ans.lower().startswith('y'):
    print('ok')
else:
    print('no')

If lowercasing the whole thing when we're only interested in the first character feels wasteful, you can slice the first character (slices don't fail with IndexErrors like ordinary indexing can):

if ans[:1].lower() == 'y':
TigerhawkT3
  • 46,954
  • 6
  • 53
  • 87
2

Make a set of your acceptable answers. This will also give you a lookup time of O(1) which may come in handy once you have a large number of acceptable answers.

acceptable_answers = {'yes', 'YES', 'y', 'Y'}
if ans in acceptable_answers:
     #do stuff
else:
     #do other stuff
timgeb
  • 73,231
  • 20
  • 109
  • 138
2

One more way:

accepted = answer.lower() in ['y','yes']
print ('ok' if accepted else 'no')
Ashalynd
  • 12,113
  • 2
  • 30
  • 36