0

I'm attempting to find out when a list is in someone's input, here's the code:

Sad = ['sad','broken','depressed','sadness','grief',]

Input = input("Hi ").strip()

if Sad in Input:
    print("Word Found")
else:
    print("Word Not Found")

It works when you have one of the words in the list alone, but when it's a sentence including the word it returns as false.

1 Answer 1

2

You're close, it's the reverse: if Input in Sad: you're trying to find an element, Input, in the Sad list ;)

If you want it to work with sentences in Input, you'll have to update your logic:

  1. Split Input into a list of word
  2. Loop on each word
  3. See if the word is present in Sad
Sad = ['sad','broken','depressed','sadness','grief',]


# split(" ") will split the string that is given as an input
# into a list of strings, using " " as a separator.
Input = input("Hi ").strip().split(" ")

for word in in Input:
    if word in Sad:
        print("Word {} Found".format(word)
    else:
        print("Word {} Not Found".format(word)

You can make this even easier using sets:


Sad = {'sad','broken','depressed','sadness','grief'}
Input = set(input("Hi ").strip().split(" "))
matching_words = Input & Sad

if matching_words:
    print("Some words found:", matching_words)
else:
    print("No words found)
Sign up to request clarification or add additional context in comments.

12 Comments

This works, but ran into the other issue. It returns false if you add another word onto it. (Responding to Agate unsure of whether the @ went through).
if you add another word onto it -> do you mean in the Input ?
Yes, when I put, "Sad", for the input it clarifies at as true but if I put, "I am sad", it clarifies it as false.
Ignore my last response, I have a literal coconut for a brain and didnt realize it prints not word for every word that isn't in the list.
I would suggest changing Sad to a set for more efficient membership checks.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.