0

I need help with this.

a = ["cat","dog","fish","hamster"]

 user = raw_input("choose your fav pet ")

if user == a[0]:

    print a[0]

elif user == a[1]:

    print a[1]

elif user == a[2]:

    print a[2]

elif user == a[3]:

    print a[3]

else:

    print "sorry, the aninimal you type does not exist"

What I want to do is a testing mobile app so I use animal as testing. The program did work but the problem is that there are over 100's of animals in the world and I put them in a list, I don't want to create many elif statements.

Is there a way to make it shorter and faster?

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
nick
  • 1
  • 2
    Is `if user in a: ...` what you seek? Then, you could simply print `user` as exactly this string is contained in your list `a` and you are done. – Michael Hoff Jul 21 '16 at 06:29
  • 1
    Possible duplicate of [Multiple conditions with if/elif statements](http://stackoverflow.com/questions/12335382/multiple-conditions-with-if-elif-statements) – NIKHIL RANE Jul 21 '16 at 06:43

5 Answers5

5

Use a for loop:

for animal in a:
    if user == animal:
        print animal
        break
else:
    print "Sorry, the animal you typed does not exist"

I'd note however that this code is a bit silly. If all you're going to do when you find the animal matching the user's entry is print it, you could instead just check if the entry is in the a list and print user if it is:

if user in a:
    print user
else:
    print "Sorry, the animal you typed does not exist"
Blckknght
  • 100,903
  • 11
  • 120
  • 169
4

I'd go with:

if user in a:
    print user

That will check if user input is in the list of pets and if it is, it will print it.

Nhor
  • 3,860
  • 6
  • 28
  • 41
0

Use in operator:

if user in a:
    print user
else : 
    print "sorry, the aninimal you type does not exist"
Puneet Tripathi
  • 412
  • 3
  • 15
0
 a = ["cat","dog","pig","cat"]
    animal = input("enter animal:")

    if animal in a:
        print (animal , "found")
    else:
        print ("animal you entered not found in the list")

The above code is apt for your requirement.

0

I would like to add a new way which i am unable to guess how every body missed. We must check string with case insensitive criteria.

a = ["cat","dog","fish","hamster"]

user = raw_input("choose your fav pet ")
// adding for user case where user might have entered DOG, but that is valid match
matching_obj = [data for data in a if data.lower() == user.lower()]

if matching_obj:
    print("Data found ",matching_obj)
else:
    print("Data not found")
Nirmal Vatsyayan
  • 384
  • 1
  • 5
  • 20