This exercise combines dictionary updates, get, and functions that share one dictionary.
add_contact with three parameters: book (a dictionary), name, and number. It stores the number under the name — adding or replacing — and returns nothing.lookup with two parameters: book and name. It returns the stored number, or the string "unknown" when the name is not in the book.contact_count with one parameter, book. It returns the number of contacts.book = {}
add_contact(book, "Ada", "555-0101")
print(lookup(book, "Ada"))
print(lookup(book, "Grace"))
Output:
555-0101
unknown
Run your code to see the output, then press Submit.
add_contact is one assignment; it needs no return.lookup is a single get with a fallback.import unittest
class TestPhoneBook(unittest.TestCase):
def test_added_contact_can_be_looked_up(self):
book = {}
add_contact(book, "Ada", "555-0101")
self.assertEqual(lookup(book, "Ada"), "555-0101")
def test_missing_contact_is_unknown(self):
self.assertEqual(lookup({}, "Grace"), "unknown")
def test_adding_again_replaces_the_number(self):
book = {"Ada": "555-0101"}
add_contact(book, "Ada", "555-0202")
self.assertEqual(lookup(book, "Ada"), "555-0202")
def test_contact_count(self):
book = {}
add_contact(book, "Ada", "1")
add_contact(book, "Grace", "2")
self.assertEqual(contact_count(book), 2)
def add_contact(book, name, number):
book[name] = number
def lookup(book, name):
return book.get(name, "unknown")
def contact_count(book):
return len(book)
book = {}
add_contact(book, "Ada", "555-0101")
print(lookup(book, "Ada"))
print(lookup(book, "Grace"))
print(contact_count(book))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.