vendredi 5 juin 2020

"if any" function won't check if strings in lists match user input. Python

So my program will ask the user for their emotional state that is contained in this variable:

emotional_state = input("How are you? ")

Beneath the input variable I have two lists filled with strings of available responses:

positive_emotion = ["good","okay", "great", "fine", "awesome", "fine thanks", "great thanks", "happy"]
negative_emotion = ["bad","not so good", "unhappy", "sad", "lonely", "depressed", "sick", "ill", "suicidal"]

The rest of the code is a series of if statements for the outputs, based on the word from the lists used.

if any([emotion in emotional_state for emotion in positive_emotion]):
    print("I'm happy to hear that :)")
elif any([emotion in emotional_state for emotion in negative_emotion]):
    print("Aww hopefully I can make you feel better :)")
else:
    print("I didn't quite catch that but let's move on, okay?")

The majority of the available responses gives the desired response however when I use a word for the input which is similar to a word from the other list, I get a response for the opposite emotion. Here is a desired output for example,

How are you? good
I'm happy to hear that :)

Now here is the bug or error that I've run into,

How are you? not so good 
I'm happy to hear that :)

It's as if the user input "not so good" (despite being from the negative_emotion list), because it contains the word "good", which is also in the positive_emotion list, is likely being mistaken for a positive_emotion.

Does anyone know what is causing this problem or have any solution?

Thanks in advance! :)

Aucun commentaire:

Enregistrer un commentaire