Contact Book Management in Python

Introduction

This Contact Book Management project is a command-line application written in Python. It allows users to create, read, update, and delete contacts, simulating a simple contact management system. This project is an excellent way to practice basic Python skills, such as working with functions, loops, conditional statements, and dictionaries.

Prerequisites

To get the most out of this project, you should be familiar with the following Python concepts:

  • Basic Python syntax
  • Functions and function calls
  • Conditional statements (if, elif, else)
  • Loops (while)
  • Data structures (dictionaries)
  • Input and output operations

Learning Objectives

By completing this project, you will:

  • Understand how to manipulate data using dictionaries in Python
  • Learn to implement basic CRUD (Create, Read, Update, Delete) operations
  • Develop a command-line interface for interacting with users
  • Practice using loops and conditional logic to control program flow

Installation Guide

To run this project on your machine, ensure you have Python installed. Follow these steps:

  1. Download and Install Python: Visit the official Python website to download and install Python if you haven’t already.
  2. Set Up a Python Environment: Use a code editor like Visual Studio Code or an IDE like PyCharm to write and run your code.
  3. Clone or Copy the Code: Copy the project code provided below into a new Python file in your development environment.

Project Steps

  1. Define Functions: Implement functions for creating, reading, updating, and deleting contacts.
  2. Build User Interface: Develop a command-line interface that allows users to interact with the contact book.
  3. Integrate Functions: Use a loop to manage the program flow and call the appropriate function based on user input.

Code

				
					#-------------Create New Contact----------------------
def create():
    while 1:
        print("\n----------------------Create  New Contact----------------------")
        name = input("Enter Name or press 0 for exit:").lower()
        if name == '0':
            break
        if name not in d:
            mob = input("Enter Mobile Number or press 0 for exit:")
            if mob == '0':
                break
            if mob not in list(d.values()):
                d.update({name:mob})
                print("Successfully added new contact")
                break
            else:
                print('''This Mobile Number already exists''')
                print("With this Name:",list(d.keys())[list(d.values()).index(mob)].title())
                c = input('''Press for
(1)Update Contact
(2)Exit
''')
                if c == "1":
                    update()
                    return
                else: pass
        else:
            print('''Contact already exists''')
        
#--------------Search Existing Contact------------------------
def read():
    print("\n----------------------Search Existing Contact----------------------")
    r = input("Enter Contact Name or Contact Number:").lower()
    if r.isdigit():
        if r in list(d.values()):
            n= list(d.keys())[list(d.values()).index(r)]
            print("Contact Name:",n.title())
            print("Contact Number:",r)
            return n
        else:
            print("Number not in Contacts")
            return 0
    else:
        if r in d:
            print("Contact Name:",r.title())
            print("Contact Number:",d[r])
            return r
        else:
            print('''Contact doesn't Exist''')
            return 0
        
#-------------Update Existing Contact------------------------
def update():
    print("\n----------------------Update Existing Contact----------------------")
    v = read()
    if v == 0:
        return
    else:
        n=input("Enter new Contact Name or Contact Number:").lower()
        if n.isdigit():
            d[v] = n
            print("Contact Updated Successfully")
        else:
            x = d.pop(v)
            print(x)
            d.update({n:x})
            print("Contact Updated Successfully")
            
#-------------Delete Existing Contact------------------------
def delete():
    print("\n----------------------Delete Existing Contact----------------------") 
    v = read()
    if v == 0:
        return
    else:
        d.pop(v)
        print("Deleted Sucessfully")
        
        
#----------------------Main Code---------------------------
print("----------------------Welcome Contact Book Management----------------------")
d = {}
while 1:
    b = input('''Choose one option
    (1) New Contact
    (2) Search Contact 
    (3) Update Contact
    (4) Delete Contact
    (5) Exit
    ''')
    if   b == "1": create()
    elif b == "2": read()
    elif b == "3": update()
    elif b == "4": delete()
    elif b == "5":
        print("Thank You!")
        break
    else:
        print('''You Choose Incorrect Option
        Please Choose Correct One''')
				
			

Code

				
					#-------------Create New Contact----------------------
def create():
    while 1:
        print("\n----------------------Create  New Contact----------------------")
        name = input("Enter Name or press 0 for exit:").lower()
        if name == '0':
            break
        if name not in d:
            mob = input("Enter Mobile Number or press 0 for exit:")
            if mob == '0':
                break
            if mob not in list(d.values()):
                d.update({name:mob})
                print("Successfully added new contact")
                break
            else:
                print('''This Mobile Number already exists''')
                print("With this Name:",list(d.keys())[list(d.values()).index(mob)].title())
                c = input('''Press for
(1)Update Contact
(2)Exit
''')
                if c == "1":
                    update()
                    return
                else: pass
        else:
            print('''Contact already exists''')
        
#--------------Search Existing Contact------------------------
def read():
    print("\n----------------------Search Existing Contact----------------------")
    r = input("Enter Contact Name or Contact Number:").lower()
    if r.isdigit():
        if r in list(d.values()):
            n= list(d.keys())[list(d.values()).index(r)]
            print("Contact Name:",n.title())
            print("Contact Number:",r)
            return n
        else:
            print("Number not in Contacts")
            return 0
    else:
        if r in d:
            print("Contact Name:",r.title())
            print("Contact Number:",d[r])
            return r
        else:
            print('''Contact doesn't Exist''')
            return 0
        
#-------------Update Existing Contact------------------------
def update():
    print("\n----------------------Update Existing Contact----------------------")
    v = read()
    if v == 0:
        return
    else:
        n=input("Enter new Contact Name or Contact Number:").lower()
        if n.isdigit():
            d[v] = n
            print("Contact Updated Successfully")
        else:
            x = d.pop(v)
            print(x)
            d.update({n:x})
            print("Contact Updated Successfully")
            
#-------------Delete Existing Contact------------------------
def delete():
    print("\n----------------------Delete Existing Contact----------------------") 
    v = read()
    if v == 0:
        return
    else:
        d.pop(v)
        print("Deleted Sucessfully")
        
        
#----------------------Main Code---------------------------
print("----------------------Welcome Contact Book Management----------------------")
d = {}
while 1:
    b = input('''Choose one option
    (1) New Contact
    (2) Search Contact 
    (3) Update Contact
    (4) Delete Contact
    (5) Exit
    ''')
    if   b == "1": create()
    elif b == "2": read()
    elif b == "3": update()
    elif b == "4": delete()
    elif b == "5":
        print("Thank You!")
        break
    else:
        print('''You Choose Incorrect Option
        Please Choose Correct One''')
				
			

Pseudo Code explaining this Python Project

				
					Here is a high-level pseudo code that outlines the logic of the Contact Book Management project:
sql
Initialize an empty dictionary to store contacts

Define function create():
    Prompt user for contact name
    If name exists, inform user and exit function
    Prompt user for mobile number
    If number exists, offer options to update or exit
    If new contact, add to dictionary

Define function read():
    Prompt user for contact name or number
    If contact exists, display name and number
    If not, inform user and return 0

Define function update():
    Call read() to get contact
    If contact found, prompt for new name or number
    Update contact information

Define function delete():
    Call read() to get contact
    If contact found, delete from dictionary

In the main loop:
    Display menu options
    Prompt user for choice
    Call corresponding function based on user input
    If user chooses exit, break loop

				
			

Pseudo Code explaining this Python Project

				
					Here is a high-level pseudo code that outlines the logic of the Contact Book Management project:
sql
Initialize an empty dictionary to store contacts

Define function create():
    Prompt user for contact name
    If name exists, inform user and exit function
    Prompt user for mobile number
    If number exists, offer options to update or exit
    If new contact, add to dictionary

Define function read():
    Prompt user for contact name or number
    If contact exists, display name and number
    If not, inform user and return 0

Define function update():
    Call read() to get contact
    If contact found, prompt for new name or number
    Update contact information

Define function delete():
    Call read() to get contact
    If contact found, delete from dictionary

In the main loop:
    Display menu options
    Prompt user for choice
    Call corresponding function based on user input
    If user chooses exit, break loop

				
			

Flow Chart

Code Explanation

  • Global Dictionary: The dictionary d is used to store contacts with names as keys and mobile numbers as values.
  • Create Function: The create() function adds a new contact if both the name and number are unique. It also handles user input validation.
  • Read Function: The read() function searches for a contact by name or number and displays the result if found.
  • Update Function: The update() function modifies an existing contact’s information. It prompts the user to input either a new name or number.
  • Delete Function: The delete() function removes a contact from the dictionary after confirming its existence.
  • Main Loop: This loop continuously prompts the user for an action, invoking the appropriate function based on user input, until the user decides to exit.

Challenges and Solutions

Challenge 1: Handling Duplicate Contacts

Solution: The code checks for existing contacts by both name and number before adding a new contact, preventing duplicates.

Challenge 2: Input Validation

Solution: The code includes checks for valid input at each step, such as ensuring names are not empty and numbers are unique.

Testing

To test this application:

  1. Add Contacts: Use the create function to add new contacts. Check that the application correctly adds contacts and handles duplicates.
  2. Search Contacts: Test the read function by searching for existing and non-existing contacts.
  3. Update Contacts: Modify contact details and verify that updates are successful.
  4. Delete Contacts: Remove contacts and confirm they are no longer in the contact book.
  5. Exit Program: Ensure that selecting the exit option terminates the application gracefully.

Additional Resources

FAQs

Q: How do I handle empty input when adding a contact?
A: The code should include checks to ensure that neither the name nor the mobile number is left empty when creating a new contact.

Q: Can I store additional information for each contact, such as email or address?
A: Yes, you can modify the dictionary structure to store additional information. Consider using nested dictionaries where each contact’s value is another dictionary containing multiple fields.

Q: How can I make this project more advanced?
A: Consider adding features like saving the contact list to a file, sorting contacts, or implementing a graphical user interface (GUI) using libraries like Tkinter or PyQt.

Project by Akshat Rajawat and Documented by Aakarsh Pandey, Team edSlash.