I am trying to find a way to make the following (sample) code more elegant:
if answer == "yes" or "Yes" or "Y" or "y" or "why not":
print("yeah")
In the same manner there in english you would not say:
The possible answers are yes or Yes or Y or why not.
and you would rather say:
The possible answers are yes, Yes, Y or why not.
What would the more elegant way of doing this would be?
Thanks in advance!!
Option 1:
answer in ["yes", "Yes", "Y", "y", "why not"]… not a good idea, builds a list each time you run it.Option 2:
answer in ("yes", "Yes", "Y", "y", "why not")… better idea, the (constant, immutable) tuple is built at compile time.Option 3: do this once:
allowables = set(["yes", "Yes", "Y", "y", "why not"])and then use
answer in allowableseach time you need it. This is the best approach when the number of allowable values is large, or the set of allowable values can vary at run-time.