-2

I want to match the correct terms from my list. Here is my code:

stuff = ["cat", "dog", "house", "cat", "mouse"]

for item in stuff:
    if "house" in item:
        print "house good"
    if "cat" in item:
        print "cat good"
    if "dog" in item:
        print "dog good"
    else:
        print "nothing else"

The results are currently this:

cat good
nothing else
dog good
house good
nothing else
cat good
nothing else
nothing else

But I want the results to be this:

cat good
dog good
house good 
cat good 
nothing else

Currently the script keeps pulling "nothing else" because of my else statement. But I don't know how to only making "nothing else" come up exclusively when a term in my list doesn't match the terms in my if statements. Does anyone know I can do this?

semiflex
  • 1,176
  • 3
  • 25
  • 44

5 Answers5

3

You should be using elif, like so:

for item in stuff:
    if "house" in item:
        print "house good"
    elif "cat" in item:
        print "cat good"
    elif "dog" in item:
        print "dog good"
    else:
        print "nothing else"

Otherwise the else only applies to the last if.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

You should make all the conditions part of the same statement, by using elif. Currently the else only applies to the last condition.

if "house" in item:
    print "house good"
elif "cat" in item:
    print "cat good"
elif "dog" in item:
    print "dog good"
else:
    print "nothing else"
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

you must use elif condition like :

stuff = ["cat", "dog", "house", "cat", "mouse"]

for item in stuff:
    if "house" in item:
        print ("house good")
    elif "cat" in item:
        print ("cat good")
    elif "dog" in item:
        print ("dog good")
    else:
        print ("nothing else")
D.Paul
  • 1
  • 1
0

Other answers suggest that you should be using a elif statement to fix your code. This is perfectly reasonable. However, I just wanted to point out that with a slight refactoring of your code you can make it simpler, more readable, and more extendable:

stuff = ["cat", "dog", "house", "cat", "mouse"]
good_stuff = set(["house", "cat", "dog"])

for item in stuff:
    if item in good_stuff:
        print item + " good"
    else:
        print "nothing else"

Any time that you find yourself using if, elif, elif, elif, ... it is usually because you have designed your code badly.

Note that I am using a set here for optimisation purposes. If you don't know why, then I suggest you look here.

Community
  • 1
  • 1
Lee Netherton
  • 21,347
  • 12
  • 68
  • 102
0

Try not to use 'in', if I was you I will try to use '=='.

But judging that it is already in the list, so you won't need the 'for' part I guess, just 'if xxx in stuff'

Hope this helps!