I am making a contact Book to store Name, Phone, and Email using entry level Python but need some help.
Here is what I have:
class ContactBook:
def init(self):
self.contacts = {} # Initialize an empty dictionary to store contacts
def add_contact(self, name, phone, email):
"""Add a new contact."""
if name in self.contacts:
print(f"Contact '{name}' already exists.")
else:
self.contacts[name] = {'Phone': phone, 'Email': email}
print(f"Contact '{name}' added successfully.")
def remove_contact(self, name):
"""Remove a contact."""
if name in self.contacts:
del self.contacts[name]
print(f"Contact '{name}' removed successfully.")
else:
print(f"Contact '{name}' not found.")
def update_contact(self, name, phone=None, email=None):
"""Update an existing contact."""
if name in self.contacts:
if phone:
self.contacts[name]['Phone'] = phone
if email:
self.contacts[name]['Email'] = email
print(f"Contact '{name}' updated successfully.")
else:
print(f"Contact '{name}' not found.")
def view_contact(self, name):
"""View details of a contact."""
if name in self.contacts:
print(f"Contact '{name}':")
print(f" Phone: {self.contacts[name]['Phone']}")
print(f" Email: {self.contacts[name]['Email']}")
else:
print(f"Contact '{name}' not found.")
def search_contact(self, search_term):
"""Search for a contact by name, phone number, or email address.
Args:
search_term (str): The term to search for (name, phone, or email).
Returns:
list: A list of matching contacts (if any)."""
matching_contacts = []
for name, contact_info in self.contacts.items():
if search_term.lower() in name.lower():
matching_contacts.append(name)
elif search_term.lower() in contact_info['Phone'].lower():
matching_contacts.append(name)
elif search_term.lower() in contact_info['Email'].lower():
matching_contacts.append(name)
if matching_contacts:
print(f"Matching contacts for '{search_term}':")
for contact_name in matching_contacts:
print(f'' {contact_name}'')
else:
print(f"No contacts found for '{search_term}'.")
Print out a contact book
New contributor
ProtonL is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.