Search code examples
pythonlistif-statementcomparison-operators

Trouble with checking and condensing lists of conditions in strings


I've been making a sort of artificial intelligence (it's more like a long list of question - answer situations) and I've been looking to step up the complexity, but I know there's a way to shorten the amount of typing I have to do and I can't quite find it. Anyways, here's the long version of me asking for input, then checking the type of input (for example it's a question):

a = input()
if "what" in a:
    a_type = question
if "where" in a:
    a_type = question
if "when" in a:
    a_type = question
if "why" in a:
    a_type = question
if "who" in a:
    a_type = question

and so on, then I would check for subject, mood, expression, etc... If anybody knows how to condense all 5 of those statements that'd be great, thanks...


Solution

  • Use the any() function with a generator expression to test words from a sequence against a:

    question_words = ['what', 'when', 'where', 'why', 'who']
    if any(word in a for word in question_words):
        a_type = question
    

    any() iterates over the generator expression and returns True as soon as one of the word in a tests is true, or False when the generator expression is exhausted.