python if ... elif总是不工作

时间:2013-12-17 12:13:03

标签: python

很抱歉发布这样一个天真的问题,但我只是无法解决这个问题。我写了以下条件语句:

if taxon == "Bracelets":
    catId = "178785"
elif taxon == "Kids Earrings" or "Earrings":
    catId = "177591"
elif taxon == "Mangalsutras":
    catId = "177595"
elif taxon == "Necklaces" or "Necklace Sets":
    catId = "177597"
elif taxon == "Kids Pendants" or "Pendants":
    catId = "177592"
elif taxon == "Pendant Sets":
    catId = "177593"
elif taxon == "Anklets":
    catId = "178788"
elif taxon == "Toe Rings":
    catId = "178787"
elif taxon == "Rings":
    catId = "177590"
else:
    print "no match\n"

但无论分类单位的价值是什么,它总是落在第二个条件下,即

elif taxon == "Kids Earrings" or "Earrings":
    catId = "177591"

因此,catId的值仍为177591

7 个答案:

答案 0 :(得分:13)

这应该是

elif taxon == "Kids Earrings" or taxon == "Earrings":

您的原始代码会测试"Earrings"的真值,而不是taxon是否具有值"Earrings"

>>> bool("Earrings")
True

更好的结构方法是使用字典:

id_map = {}
id_map["Bracelets"] = "178785"
id_map["Earrings"] = "177591"
id_map["Kids Earrings"] = "177591"
# etc

然后你可以做

id_map[taxon]

这也可以更好地存储在配置文件或数据库中,以避免对Python代码中的值进行硬编码。

答案 1 :(得分:7)

其他人已经为你的问题提供了语法答案。

我的回答是更改这个丑陋的代码以使用字典查找。例如:

taxes = {"Bracelets": 178785, "Necklaces": 177597, "Necklace Sets": 177597}
#etc

然后你使用

catId = taxes[taxon]

答案 2 :(得分:3)

使用这个成语:

elif taxon in ("Kids Earrings", "Earrings"):

答案 3 :(得分:1)

问题在于,它总是为真,因为它会计算布尔值True,它会检查字符串是否为空。

更改为:

if taxon == "Bracelets":
    catId = "178785"
elif taxon == "Kids Earrings" or taxon == "Earrings":
    catId = "177591"
elif taxon == "Mangalsutras":
    catId = "177595"
elif taxon == "Necklaces" or taxon == "Necklace Sets":
    catId = "177597"
elif taxon == "Kids Pendants" or taxon == "Pendants":
    catId = "177592"
elif taxon == "Pendant Sets":
    catId = "177593"
elif taxon == "Anklets":
    catId = "178788"
elif taxon == "Toe Rings":
    catId = "178787"
elif taxon == "Rings":
    catId = "177590"
else:
    print "no match\n

在个人笔记中我会使用python dict非常好,而不是if else:

options = {"option1": "value1", "option2": "value2".....}

答案 4 :(得分:1)

这个条件:

taxon == "Kids Earrings" or "Earrings"

看起来像

(taxon == "Kids Earrings") or "Earrings"

始终为true,因为"Earrings"计算为true(非空字符串)。

你想做:

taxon in ("Earrings, "Kids Earrings")

或只写几个条件:

taxon == "Earrings" or taxon == "Kids Earrings"

或者也许:

taxon.endswith("Earrings")

答案 5 :(得分:1)

使用

elif taxon in ("Kids Earrings", "Earrings"):

答案 6 :(得分:0)

不对变量检查第二个条件。这样没有意义! 试试这种方式:

...
elif taxon == "Kids Earrings" or taxon == "Earrings":
    catId = "177591"
...