CSCI-101: Intro to Computer Science
Python Course

Phonebook Dictionary Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Title: Phonebook Dictionary Example
# Author: Jack Rosenthal

# Kind programs always welcome their guests!
print("Welcome to the phone book!")

# Let's create an empty dictionary to store our entries in
book = {}

# Repeat this loop until they exit
while True:
    # Print the menu options
    print("What would you like to do?")
    print("    1 - Add an entry")
    print("    2 - Lookup an entry")
    print("    3 - Delete an entry")
    print("    4 - Exit")
    choice = input("Enter an option: ")
    if choice == '1':
        name = input('Name: ')
        phone = input('Telephone Number: ')
        book[name] = phone
    elif choice == '2':
        name = input('Name: ')
        # This will cause a KeyError if name is not in book's keys
        # Think about how you might add error handling to this...
        # You can take advantage of "if name in book.keys()"
        print("Their number is:", book[name])
    elif choice == '3':
        name = input('Name: ')
        # This will also cause a KeyError if name is not a key
        del book[name]
    elif choice == '4':
        # exit the loop
        break
    else:
        print('Invalid option.')