4

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
  • 30,354
  • 12
  • 88
  • 93
Pol Hallen
  • 1,852
  • 6
  • 32
  • 44
  • 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
  • 30,354
  • 12
  • 88
  • 93
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
  • 48,464
  • 6
  • 60
  • 97
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
  • 76,762
  • 20
  • 123
  • 145
2

One more way:

accepted = answer.lower() in ['y','yes']
print ('ok' if accepted else 'no')
Ashalynd
  • 12,363
  • 2
  • 34
  • 37