Welcome! Today, we will explore creating a simple address book application using Python dictionaries. This task will help you understand manipulating dictionaries in Python, focusing on adding, retrieving, and deleting entries. By the end of this lesson, you'll have a solid grasp of these fundamental operations.
In this task, we will implement three methods to manage our address book:
add_contact(self, name: str, phone_number: str) -> bool: Adds a new contact. ReturnsFalseif the contact already exists, otherwise adds the contact and returnsTrue. In this task, let's assume phone numbers do not change, so it's not allowed to overwrite the existing contact's number.get_contact(self, name: str) -> str | None: Retrieves the phone number for a givenname. ReturnsNoneif the contact does not exist.delete_contact(self, name: str) -> bool: Deletes a contact with the givenname. ReturnsTrueif the contact exists and is deleted,Falseotherwise.
Let's break down each method in detail in the next sections.
This method adds a new contact to the address book with the given name and phone_number. If the contact already exists, it returns False. Otherwise, it adds the contact and returns True.
Question: Why do you think we need to check if the contact already exists?
Answer: To avoid duplicating existing entries. If a contact with the same name already exists, we shouldn't allow overwriting its phone number in this method, as it's only for creation.
Here is the method implementation:
In this method:
- We verify if the contact already exists using
if name in self.contacts. - If it exists, we return
False. - If it doesn't exist, we add it to our dictionary and return
True.
