Home > OS >  How to compare the input statement with the mood list like if I entered I am fine in input?
How to compare the input statement with the mood list like if I entered I am fine in input?

Time:04-09

mood = ['Fine', 'bad', 'good', 'sad', 'angry']
a = input("how are You  ").split()
print(a)

CodePudding user response:

Try this man maybe it will work :)

a = a.strip()
If "fine" in a:
{
    print(mood[0])
}
If "bad" in a:
{
    print(mood[1])
}

CodePudding user response:

You could loop over the list and compare each element:

moods = ['fine', 'bad', 'good', 'sad', 'angry']
mymood = input("how are You  ").strip()

for mood in moods:
    if mymood == mood:
        break
else:
    raise ValueError("I can't tell your mood")

But there are better ways in Python. You can use the containment operator, in.

if mymood not in moods:
    raise ValueError("I can't tell your mood")

Even better if moods was a set.


moods = {'fine', 'bad', 'good', 'sad', 'angry'}

# The test looks exactly the same, but will be faster for large sets.
if mymood not in moods:
    raise ValueError("I can't tell your mood")

After that, the mymood variable is known to be one of the moods.

  • Related