写得更少的elif声明

0 python if-statement python-2.7

我需要帮助.

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"
Run Code Online (Sandbox Code Playgroud)

我想要做的是测试移动应用程序,所以我使用动物作为测试.该计划确实有效,但问题是世界上有超过100种动物,我将它们列入清单,我不想创建许多elif声明.

有没有办法让它更短更快?

Blc*_*ght 5

使用for循环:

for animal in a:
    if user == animal:
        print animal
        break
else:
    print "Sorry, the animal you typed does not exist"
Run Code Online (Sandbox Code Playgroud)

但是我注意到这段代码有点傻.如果当你发现匹配用户条目的动物打印它时你要做的就是打印它,你可以只检查条目是否在a列表中,print user如果是:

if user in a:
    print user
else:
    print "Sorry, the animal you typed does not exist"
Run Code Online (Sandbox Code Playgroud)