Simple Python Contact Info Book

I'm trying to make a basic contact information book with python. The user can search or add contacts. Here is my code.

address_book = {}
print('''1 - Add/Update contact
2 - Search
''')

def update_contact():
    name = input("Enter a name: ")
    phone_number = input("Enter a phone number: ")
    address_book[name] = phone_number
def search():
    search_key = input("Search for a name: ")
    for key, value in address_book.items():
        if key == search_key:
            print("Name:" + search_key)
            print("Phone Number: " + address_book[search_key])
            return
        else:
            print("No such contact was found in the address book")
            return
run = True
def quitfunc():
    global run
    print("Program Stopped.")
    run = False

while (run):
    print("")
    option = input("Choose a option: ")
    if (option == "1"):
        print("")
        update_contact()
        
    elif (option == "2"):
        print("")
        search()
        
    else:
        quitfunc()    

The update_contact function works fine, but the search function only works for the first person you search up. If you try to make a second contact, the search function doesn't work with that person. What is wrong if my code? Thanks!


Solution 1:

Use this instead for your search function:

def search():
    search_key = input("Search for a name: ")
    if search_key in address_book:
        print("Name:", search_key);
        print("Phone number:", address_book[search_key])
    else:
        print("No such contact was found in the address book")

You don't need to iterate over a for loop in order to search for a key in the dictionary. A simple if..in statement works.