if else中的Python字典

时间:2013-07-24 18:54:34

标签: python loops dictionary

我想在输入他的名字时看到johns号码。 首先想要这样做:

def liste_kontrol(liste):
    liste=raw_input("Name pls:")
    if liste=="john":
        print "now u seeng on list",john,"number."
    else:
        print "cant found"
liste={"john":002050505",} 
liste_kontrol(liste)

也许接下来:

def liste_kontrol(liste):
    liste=raw_input("Name pls:")
    if liste=="john" or "jack:
        print "now u seeng on list", john, or jack, "number."
    else:
        print "cant found."
liste= {"john":"002050505","jack":"0551282"}
liste_kontrol(liste)

2 个答案:

答案 0 :(得分:1)

理想情况下,您应该在此处使用异常处理,并查看列表的前面,尝试:

names = {
    "john": "002050505",
    "jack": "0551282"
}

name = raw_input('Enter a name:')

try:
    print "{}'s number is {}".format(name, names[name])
except KeyError as e:
    print "Couldn't find {}".format(name)

这避免了必须在有效名称中编程作为if条件的一部分,并预先检查您是否具有名称的相关值。

答案 1 :(得分:0)

好像你正试图这样做:

def liste_kontrol(liste):
    name=raw_input("Name pls:")
    if name in liste:
        print "now u seeng on list", name, liste[name]
    else:
        print "cant found."
liste= {"john":"002050505","jack":"0551282"}
liste_kontrol(liste)