写少elif陈述

时间:2016-07-21 06:25:35

标签: python python-2.7 if-statement

我需要帮助。

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"

我想要做的是测试移动应用程序,所以我使用动物作为测试。该程序确实有效,但问题是世界上有超过100种动物,我将它们放在一个列表中,我不想创建许多elif语句。

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

5 个答案:

答案 0 :(得分:5)

使用for循环:

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

但是我注意到这段代码有点傻。如果您发现匹配用户条目的动物打印时,您只需检查该条目是否在a列表中,如果是print user,则可以:

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

答案 1 :(得分:4)

我会选择:

if user in a:
    print user

这将检查user输入是否在宠物列表中,如果是,则会打印出来。

答案 2 :(得分:0)

在运营商中使用:

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

答案 3 :(得分: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")

以上代码适合您的要求。

答案 4 :(得分:0)

我想添加一种新的方式,我无法猜测每个身体是如何错过的。我们必须使用不区分大小写的标准检查字符串。

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