EnochDuah 5 months ago
enochduah #homeworkhelp

This program is supposed to manage names, addresses, phonenumbers, and other …

Question: This program is supposed to manage names, addresses, phonenumbers, and other contact-related information.Features:The Address Book is a collection of records and onerecord should have following fields about a contact · Name· Address· Phone number· This program is supposed to manage names, addresses, phonenumbers, and other contact-related information. Features: The Address Book is a collection of records and onerecord should have following fields about a contact · Name · Address · Phone number · Email address The Address Book program should have the following features Add-to add a new person record Delete-to delete an existing person record Modify-to change an existing record Search- to search a person record By name By phone number View All contacts Exit –to exit from application Address Book should also support persistence for personrecords Supporting simple persistence by any application requireshandling of two scenarios On start up of application-data (person records) must beread from file. On end/finish up of application -data (person records)must be saved in file. program is supposed to manage names, addresses, phonenumbers, and other contact-related information.Features:The Address Book is a collection of records and onerecord should have following fields about a contact · Name· Address· Phone number· This program is supposed to manage names, addresses, phonenumbers, and other contact-related information. Features: The Address Book is a collection of records and onerecord should have following fields about a contact · Name · Address · Phone number · Email address The Address Book program should have the following features Add-to add a new person record Delete-to delete an existing person record Modify-to change an existing record Search- to search a person record By name By phone number View All contacts Exit –to exit from application Address Book should also support persistence for personrecords Supporting simple persistence by any application requireshandling of two scenarios On start up of application-data (person records) must beread from file. On end/finish up of application -data (person records)must be saved in file.

import os
import pickle

class Contact:
    def __init__(self, name, address, phone, email):
        self.name = name
        self.address = address
        self.phone = phone
        self.email = email
    
    def __str__(self):
        return f"Name: {self.name}\nAddress: {self.address}\nPhone: {self.phone}\nEmail: {self.email}"

class AddressBook:
    def __init__(self):
        self.contacts = []
        self.data_file = "contacts.dat"
        self.load_contacts()
    
    def add_contact(self, contact):
        self.contacts.append(contact)
        print("Contact added successfully!")
    
    def delete_contact(self, name):
        initial_len = len(self.contacts)
        self.contacts = [c for c in self.contacts if c.name.lower() != name.lower()]
        return len(self.contacts) < initial_len
    
    def modify_contact(self, name, new_contact):
        for i, contact in enumerate(self.contacts):
            if contact.name.lower() == name.lower():
                self.contacts[i] = new_contact
                return True
        return False
    
    def search_by_name(self, name):
        return [c for c in self.contacts if name.lower() in c.name.lower()]
    
    def search_by_phone(self, phone):
        return [c for c in self.contacts if phone in c.phone]
    
    def save_contacts(self):
        try:
            with open(self.data_file, 'wb') as f:
                pickle.dump(self.contacts, f)
            print("Contacts saved!")
        except Exception as e:
            print(f"Error saving: {e}")
    
    def load_contacts(self):
        if os.path.exists(self.data_file):
            try:
                with open(self.data_file, 'rb') as f:
                    self.contacts = pickle.load(f)
                print(f"Loaded {len(self.contacts)} contacts.")
            except Exception as e:
                print(f"Error loading: {e}")
                self.contacts = []

def main():
    address_book = AddressBook()
    
    def display_menu():
        print("\n===== ADDRESS BOOK MENU =====")
        print("1. Add Contact\n2. Delete Contact\n3. Modify Contact")
        print("4. Search Contact\n5. View All Contacts\n6. Exit")
        return input("Enter choice: ")
    
    def add_contact():
        print("\n--- Add New Contact ---")
        name = input("Name: ")
        address = input("Address: ")
        phone = input("Phone: ")
        email = input("Email: ")
        address_book.add_contact(Contact(name, address, phone, email))
    
    def delete_contact():
        name = input("\nName to delete: ")
        if address_book.delete_contact(name):
            print("Contact deleted!")
        else:
            print("Contact not found!")
    
    def modify_contact():
        name = input("\nName to modify: ")
        contacts = address_book.search_by_name(name)
        
        if not contacts:
            print("Contact not found!")
            return
        
        if len(contacts) > 1:
            print("Multiple contacts found. Be more specific.")
            for i, c in enumerate(contacts):
                print(f"\n--- Contact {i+1} ---\n{c}")
            return
        
        c = contacts[0]
        print("Enter new info (blank to keep current):")
        new_name = input(f"Name [{c.name}]: ") or c.name
        new_addr = input(f"Address [{c.address}]: ") or c.address
        new_phone = input(f"Phone [{c.phone}]: ") or c.phone
        new_email = input(f"Email [{c.email}]: ") or c.email
        
        new_contact = Contact(new_name, new_addr, new_phone, new_email)
        if address_book.modify_contact(c.name, new_contact):
            print("Contact modified!")
        else:
            print("Error modifying contact!")
    
    def search_contact():
        print("\n1. Search by name\n2. Search by phone")
        choice = input("Choice: ")
        
        if choice == "1":
            name = input("Name to search: ")
            contacts = address_book.search_by_name(name)
        elif choice == "2":
            phone = input("Phone to search: ")
            contacts = address_book.search_by_phone(phone)
        else:
            print("Invalid choice!")
            return
        
        if contacts:
            print(f"\nFound {len(contacts)} contacts:")
            for i, c in enumerate(contacts):
                print(f"\n--- Contact {i+1} ---\n{c}")
        else:
            print("No contacts found!")
    
    def view_all_contacts():
        if not address_book.contacts:
            print("\nNo contacts found!")
        else:
            for i, c in enumerate(address_book.contacts):
                print(f"\n--- Contact {i+1} ---\n{c}")
    
    actions = {
        "1": add_contact,
        "2": delete_contact,
        "3": modify_contact,
        "4": search_contact,
        "5": view_all_contacts
    }
    
    running = True
    while running:
        choice = display_menu()
        if choice in actions:
            actions[choice]()
        elif choice == "6":
            running = False
            address_book.save_contacts()
            print("Goodbye!")
        else:
            print("Invalid choice!")

if __name__ == "__main__":
    main()


https://youtube.com/shorts/Bliu44FM3N4?si=OIt9vWJwSPtW2q1q

0
187

explain the English empire in America in the late seventeenth/early ei...

explain the English empire in America in the late seventeenth/early eighteenth centuries....

defaultuser.png
ponips
5 months ago

You can define the compareTo method in a class withoutimplementing the...

You can define the compareTo method in a class withoutimplementing the Comparable interfac...

1746135388.png
EnochDuah
5 months ago

Question: Object models (as described for example using classdiagrams)...

Object models (as described for example using classdiagrams) often incorporate the foll...

1746135388.png
EnochDuah
4 months ago

Jim wants to identify weaknesses and monitor information security prog...

Jim wants to identify weaknesses and monitor information security progress. What type of s...

1746135388.png
EnochDuah
4 months ago
video

write a program showing the use of if else and switch statem...

enochduah
EnochDuah
4 months ago