Introduction:
In today's world, managing contacts efficiently is crucial for both personal and professional endeavors. Whether you are a freelancer, a small business owner, or just someone who wants to keep their contacts organized, having a reliable system in place can save time and effort. In this blog, we will learn the creation of a basic Contact Management System (CMS) using Python.
Method 1: Using a Dictionary
def add_contact(contacts, name, number):
contacts[name] = number
def display_contacts(contacts):
for name, number in contacts.items():
print(f"{name}: {number}")
def main():
contacts = {}
add_contact(contacts, "John Doe", "123-456-7890")
add_contact(contacts, "Jane Smith", "987-654-3210")
display_contacts(contacts)
if __name__ == "__main__":
main()
Output:
John Doe: 123-456-7890
Jane Smith: 987-654-3210
In this method, we use a dictionary to store contacts, where the keys represent the names and the values represent the phone numbers. The add_contact
function adds a new contact to the dictionary, while the display_contacts
function prints out all the contacts stored in the dictionary.
Method 2: Using Classes
class Contact:
def __init__(self, name, number):
self.name = name
self.number = number
class ContactManager:
def __init__(self):
self.contacts = []
def add_contact(self, contact):
self.contacts.append(contact)
def display_contacts(self):
for contact in self.contacts:
print(f"{contact.name}: {contact.number}")
def main():
contact_manager = ContactManager()
contact_manager.add_contact(Contact("John Doe", "123-456-7890"))
contact_manager.add_contact(Contact("Jane Smith", "987-654-3210"))
contact_manager.display_contacts()
if __name__ == "__main__":
main()
Output:
John Doe: 123-456-7890
Jane Smith: 987-654-3210
This method involves creating two classes: Contact
to represent individual contacts and ContactManager
to manage a list of contacts. Contacts are added to the ContactManager
using the add_contact
method, and then displayed using the display_contacts
method.
Conclusion:
In this blog, we have explored different methods to implement a basic Contact Management System in Python. We have started with a simple dictionary-based approach, followed by a more object-oriented approach using classes. Depending on your specific needs and preferences, you can choose the method that best suits your requirements.
Comments (0)