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")
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")
You could check it with list:
if ans in ['yes', 'YES', 'y', 'Y']:
print('ok')
else:
print('no')
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 IndexError
s like ordinary indexing can):
if ans[:1].lower() == 'y':
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
One more way:
accepted = answer.lower() in ['y','yes']
print ('ok' if accepted else 'no')