vendredi 10 avril 2020

Python: dictionary for each item matching problem

I am trying to look for a correspond value to the key in dictionary on Hackerank.

I tried to print out every process to debug, and I found the process ran quite as I expected, however, the result was really weird. my output shows that the statement did read the right name "harry", but it cannot find "harry" in my dictionary. Can someone pls give me some ideas on this, thank you!

Here are my codes:

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

sample input is:

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

expected output:

sam=99912222
Not found
harry=1229993

my output is:

{'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?

Aucun commentaire:

Enregistrer un commentaire