Python:字典中的每一项匹配问题

Python: dictionary for each item matching problem

我正在尝试在 Hacke运行k 的字典中寻找 与键 对应的值。

我试着把每一个进程都打印出来调试,发现进程运行和我预想的一样,但是,结果真的很奇怪。我的输出显示该语句确实读取了正确的名称 "harry",但它在我的字典中找不到 "harry"。有人可以给我一些想法吗,谢谢!

这是我的代码:

if __name__=='__main__':
    n = int(input()) #input how many pairs of name-phone in this phonebook
    d = dict()

    for count in range(n):
        name, phone = input().split()
        d[name] = phone
    print(d)

    while True:
        search_phone = input() #input the name
        print('enter new name') #debug

        for name, phone in d.items():
            if search_phone == name :
                print(name + '=' + phone)
                print(search_phone + ' bingle, continue to enter another name')
                break

            elif search_phone != name:
                print('Not found')
                print(search_phone + ' no match, continue to enter another name')
                break

样本输入是:

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

预期输出:

sam=99912222
Not found
harry=1229993

我的输出是:

{'sam': '99912222', 'tom': '11122222', 'harry': '12299933'}    
enter new name
sam=99912222
sam bingle, continue to enter another name
enter new name
Not found
edward no match, continue to enter another name
enter new name
Not found
harry no match, continue to enter another name 
###my question is why it did read harry but goes to no match?

那是因为你把 break 放在你的 else 语句中。因此,代码将在第一个循环处中断,并且无法获取 d 中的下一个项目。所以,你必须删除 else 语句中的 break。

但是我们有新的问题,在每个循环中都会执行else语句if search_phone != name。所以,我们已经解决了这个问题。你可以试试这个(抱歉英语不好)

 while True:
        search_phone = input() #input the name
        print('enter new name') #debug
        valid = False

        for name, phone in d.items():
            if search_phone == name :
                print(name + '=' + phone)
                print(search_phone + ' bingle, continue to enter another name')
                valid = True
                break

        if not valid:
            print('name:', name)
            print('Not found')
            print(search_phone + ' no match, continue to enter another name')