In this project we will walk through the process of creating a simple contact book application using python. This is going to be a completely beginner friendly project to start with. This application will allow user to add the basic functionality like adding, searching, updating and deleting contact information. We will walk though the code line by line and at the end the full code for the application is provided.
In the next part of this project we will use a database to store our data permanently. But in this application will store our data simply inside a list in dictionary format because this is very beginner level project for them who don’t know use of SQL .
Prerequisites:
- You should have basic Python knowledge for doing this project.
- Basic knowledge on List, Dictionary, Functions, For Loop, While loop .
- Python version 3 or higher installed on your machine, or you can use our online editor .
- A Python IDE(Code editor).
Before we dive into the coding aspect, let’s take a moment to imagine the features and logic that we’ll be incorporating into our contact book application. By visualizing the desired functionality, we can better understand how our code will bring these features to life.
Features of the Contact Book Application
Let’s take a moment to imagine the contact book on your mobile phone. By relating the functionalities of our contact book application to your real-world experience with a mobile contact book, we aim to make the concept and usage more relatable and intuitive.
Just like your mobile contact book, our application allow the following features in out this simple application.
- Add a Contact: Users will be able to add a new contact by providing the contact’s name, email, and phone number.
- Search for a Contact: Users can search for a contact by entering the contact’s name or email. The application will display any matching contacts found.
- Update a Contact: Users can update the details of an existing contact by specifying the contact’s name and entering the new name, email, and phone number.
- Delete a Contact: Users can delete a contact by specifying the contact’s name. The application will remove the contact from the contact list.
- Display All Contacts: Users can view all contacts stored in the contact book. The application will display the name, email, and phone number of each contact.
Setting Up the Project
- Create a new Python file called
contact_book.py
on your local machine. - Open the
contact_book.py
file in your code editor (PyCharm or any other Code editor).
Contact Book Application Code Explanation
Step1: Adding The Menu Function:
Let’s begin by identifying the starting point of our application since we don’t have a user interface yet. We need to provide the user with options to select the action they want to perform.
By offering a menu-based approach, users will have clear options to add, search, update, or delete contacts. This menu system will act as a command center for managing their contact book effectively.
# First Let's create a blank list contacts. We will add/append new contacts to this list.
contacts = []
def display_menu(): # This is the menu for our contact book app.Here user will select the acton he wants to perform.
print("Contact Book Menu")
print("1. Add a contact")
print("2. Search for a contact")
print("3. Update a contact")
print("4. Delete a contact")
print("5. Display all contacts")
print("6. Exit")
When you call the above function It will print all the statements inside this to help the user to select a option with.
Step2: Adding New Contact Function:
Next, we’ll tackle the essential functionality of adding contacts to our application. Since we don’t have a graphical user interface, we’ll prompt users to enter the contact details via the command-line interface. This process mirrors the manual process of saving a new contact on a mobile phone.
def add_contact():
"""
This function will be used to add new contact to our contacts list.
We are asking the user to input contact details.
"""
name = input("Enter the contact's name: ")
email = input("Enter the contact's email: ")
phone = input("Enter the contact's phone number: ")
contact = {"Name": name, "Email": email, "Phone": phone} # We are creating a dictionary using above informations
contacts.append(contact) # Then we are adding the individuall contact information in a dictionary format to our contacts list
print("Contact added successfully!")
Line no 6,7,8: Here we prompting the user to input the contact details like name, email, phone no.
Line no 9: Creating a dictionary out of the information provided by the user.
Line no 10: We are appending the dictionary to our main contacts list. So contacts list will store individual contact information in dictionary format. So it will be basically a List of Dictionary.
Stay tuned as we delve into the coding implementation of this feature, bringing us closer to a fully functional contact book application!
Step3: Adding Search Functionality:
Next, we’ll implement the search functionality in our contact book application. Users will have the ability to search for contacts by name or email, providing them with flexible options to locate specific entries within their contact book. This feature replicates the search capabilities found in mobile contact books, allowing users to conveniently find desired contacts using either their name or email.
def search_contact():
"""
This function will be used to search the existing contact from our contact book list.
The user can enter either name or email address to search the contact.
"""
search_term = input("Enter the name or email of the contact to search: ") # Asking user to input the search term.
found_contacts = [] # We are taking a blank list.Here we will store all the contacts that are matching with our search term.
for contact in contacts: # Loop through each contact stored in the contacts list and match with name or email with our search term
if search_term.lower() in contact["Name"].lower() or search_term.lower() in contact["Email"].lower():
found_contacts.append(contact) # Append the matching search result to the found_contacts declared above at line no 7
if found_contacts: # Checking if any contact is the in the found_contacts list.
print("Matching contacts found:")
for contact in found_contacts: # Looping through the found_contacts list to print each contact details that is matchoing our search term.
print("Name:", contact["Name"])
print("Email:", contact["Email"])
print("Phone:", contact["Phone"])
print("-------------------")
else:
print("No matching contacts found.")
Line No 6: We are prompting the user to enter either the contact name or email to search the contact.
Line No 7: We are taking a blank list “found_contacts“. All the matching or found contacts will be stored inside this before displaying them.
Line no 8 to 10: We are looping through the main contacts list to match our searched term and append all the matching contact to “found_contacts” list. Here in line no we are converting it to lower case on both side so that our application should search for any case(Capital or small) you give.
Line No 12 to 18: Fetching all the matching contacts stored inside “found_contacts” list and printing one by one.
Step4: Update the Contact:
Moving forward, we’ll focus on implementing the update functionality in our application. This feature allows users to modify the details of existing contacts by providing the option to update a contact’s name, email, and phone number.
def update_contact():
"""
This function will be used to edit/update the existing contact in our contacts list.
First we will search the contact if exists, if found we will update the new details.
"""
name = input("Enter the name of the contact to update: ") # Prompting the user to enter the name to update
found_contact = None # Initiating a new variable with intial value None
for contact in contacts: # Looping through the contacts list to find out if the searched contact exist.
if contact["Name"].lower() == name.lower():
found_contact = contact # Assigning the found contact from the contacts list to new variable found_contact
break
if found_contact: # Checking if the found_contact variable has a value other than none, Then asking user to input new contact details
print("Contact found. Enter new details:")
found_contact["Name"] = input("Enter the new name: ")
found_contact["Email"] = input("Enter the new email: ")
found_contact["Phone"] = input("Enter the new phone number: ")
print("Contact updated successfully!")
else:
print("Contact not found.")
Step5: Deleting a Contact From Contact List:
Next, we’ll implement the delete functionality in our contact book application. This feature allows users to remove unwanted contacts from their contact book.
def delete_contact():
"""
We will use this function to delete a contact from our contacts list.
We will search the contact by name, then if found then delete it.
"""
name = input("Enter the name of the contact to delete: ") # Prompt the user to enter the contact name which he want to delete
for contact in contacts: # Loop thorough the contacts list to find out the serached contact
if contact["Name"].lower() == name.lower(): # Contact found then remove from the list in next line
contacts.remove(contact) # Remove the found contact from contacts list
print("Contact deleted successfully!")
break
else:
print("Contact not found.")
Here first we are asking the user to input the contact they want to delete. Then Looping through the contacts list and matching the name, if found then deleting that contact from the list.
You can see we are breaking the loop once we have deleted the found contact so that the loop doesn’t continue and it does not move to he else block.
Step6: Display All Contacts:
Moving ahead, we’ll implement the display all contacts functionality in our contact book application. This feature enables users to view the entire list of contacts stored in their contact book. This allow the user to quickly browse through their collection and access vital information at a glance.
def display_all_contacts():
"""
This function will display all the contacts stored in our contacts list.
Simply select the choice to display all contacts
"""
if contacts:
print("All Contacts:")
for contact in contacts: # Loop through the contacts list and fetch all the contacts ,then display them one by one
print("Name:", contact["Name"])
print("Email:", contact["Email"])
print("Phone:", contact["Phone"])
print("-------------------") # Separator between each contact
else:
print("No contacts found.")
Step7: The Driver Loop:
After implementing all the essential functionalities of our application, we come to the final part of the code. This section represents the main program loop that drives the interaction with the contact book.
Inside the loop, we display the contact book menu using the display_menu()
function. This menu presents the available options to the user, including add, search, update, delete, display all, and exiting the program.
Based on the user’s choice, we use conditional statements (if
, elif
, and else
) to execute the corresponding functions that handle each action. For example, selecting option 1 triggers the add_contact()
function, option 2 triggers the search_contact()
function, and so on.
The loop continues until the user chooses the option to exit the program (option 6). At that point, we break out of the loop and display a message indicating the program is exiting.
# Main program loop
while True:
"""
This is the main part or entry point to our application. When we will run this file it will from this point.
This is an infinite loop,it will continue untill we give the choice "6". Based on user choice respective function will get called.
"""
display_menu()
choice = input("Enter your choice (1-6): ")
if choice == "1":
add_contact()
elif choice == "2":
search_contact()
elif choice == "3":
update_contact()
elif choice == "4":
delete_contact()
elif choice == "5":
display_all_contacts()
elif choice == "6":
print("Exiting the program...")
break # Exits the program when choice given "6"
else:
print("Invalid choice. Please enter a valid option (1-6).")
Running the Contact Book Application
To run the contact book application and start managing your contacts, follow these simple steps:
- Ensure you have Python (version 3 or higher) installed on your machine.
- Save the contact book code in the file named
contact_book.py
. - Open a terminal or command prompt and navigate to the directory where the
contact_book.py
file is located. - Run the following command to execute the application:
python contact_book.py
- Once the program starts, you will see a menu with different options. Use the provided numbers to select the action you want to perform, such as adding a contact, searching for a contact, updating a contact, deleting a contact, displaying all contacts, or exiting the program.
- Follow the prompts and enter the required information to perform the desired action.
- If you are using PyCharm or any other editor which allows to run the code directly you can simply run the code there only.
Final Thoughts:
With the completion of this code, we have successfully developed a functional contact book application in Python. However, feel free to further enhance the code, add additional features, or customize it to meet your specific requirements.
In the next part of the tutorial we will see how to use database to store our contacts data permanently and use email functionality as well.
If you have any questions please comment below.