syafihakim
syafihakim

Reputation: 89

Python - Find input answer in a list, answer is one of the list element

Let say I ask the user whether to start the quiz and there a possibilities of answer like yes, yeah, and yea.

I want to put the possible answer in a list and make python runs through every single of the element in the list and check if they are equal.

if answer.lower() == 'yeah yes yep yea'.split(): 
    .... blocks of code ....

Upvotes: 1

Views: 1357

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250971

Use in operator:

if answer.lower() in 'yeah yes yep yea'.split():

Demo:

>>> 'YeAH'.lower() in 'yeah yes yep yea'.split()
True
>>> 'Yee'.lower() in 'yeah yes yep yea'.split()
False

It's better to define the list/tuple first instead if creating a list each time(In case you're doing this is a loop):

>>> lis = 'yeah yes yep yea'.split()
>>> 'yes' in lis
True

In Python3.2+ it is recommended to use set literals:

Python’s peephole optimizer now recognizes patterns such x in {1, 2, 3} as being a test for membership in a set of constants. The optimizer recasts the set as a frozenset and stores the pre-built constant.

Now that the speed penalty is gone, it is practical to start writing membership tests using set-notation. This style is both semantically clear and operationally fast:

if answer.lower() in {'yeah', 'yes', 'yep', 'yea'}:
    #pass

Upvotes: 2

jramirez
jramirez

Reputation: 8685

Instead of using a string then splitting why don't you use a list of your possible answers?

if answer.lower() in ['yes', 'yeah', 'Yeah', 'yep', 'yea']: # you can add more options to the list
    # code

Upvotes: 0

Related Questions