nick
nick

Reputation: 1

Writing less elif statement

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?

Upvotes: 0

Views: 122

Answers (5)

Nirmal Vatsyayan
Nirmal Vatsyayan

Reputation: 414

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")

Upvotes: 0

Chakradhar Burra
Chakradhar Burra

Reputation: 1

 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.

Upvotes: 0

Puneet Tripathi
Puneet Tripathi

Reputation: 422

Use in operator:

if user in a:
    print user
else : 
    print "sorry, the aninimal you type does not exist"

Upvotes: 0

Blckknght
Blckknght

Reputation: 104792

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"

Upvotes: 5

Nhor
Nhor

Reputation: 3940

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.

Upvotes: 4

Related Questions