Trufa
Trufa

Reputation: 40747

Python - How to group variables separated by or/and operators

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!!

Upvotes: 2

Views: 784

Answers (3)

John Machin
John Machin

Reputation: 83032

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 allowables each 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.

Upvotes: 6

Rumple Stiltskin
Rumple Stiltskin

Reputation: 10425

Following code does the same thing:

if answer in ["yes", "Yes", "Y", "y", "why not"]:
    print "yeah"

Upvotes: 1

Ben Blank
Ben Blank

Reputation: 56634

You can use the in operator to compare against a list:

if answer in ["yes", "Yes", "Y", "y", "why not"]:
    print("yeah")

Upvotes: 3

Related Questions