if els中的Python词典

2024-05-15 01:08:46 发布

您现在位置:Python中文网/ 问答频道 /正文

当我输入约翰的名字时,我想看看他的号码。 首先要做的是:

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)

Tags: nameinputrawifondefjohnnow
2条回答

似乎你在尝试这样做:

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)

理想情况下,您应该在这里使用异常处理,并在列表前面查找,然后尝试:

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条件的一部分,必须在有效名称中编程,并预先检查名称是否有相关值。你知道吗

相关问题 更多 >

    热门问题