Python Major Topic Exp
Python Major Topic Exp
We'll build a
simple contact management system that covers several key topics:
2. File Handling
3. Exception Handling
5. Functions
This system allows users to add, view, and delete contacts. Contacts are stored in a file, and the
program will handle errors gracefully.
**************
class Contact:
self.name = name
self.phone = phone
self.email = email
def __str__(self):
**************
This class will manage the contacts, including loading from and saving to a file:
**************
import json
class ContactManager:
self.filename = filename
self.contacts = self.load_contacts()
def load_contacts(self):
try:
data = json.load(file)
except FileNotFoundError:
return []
except json.JSONDecodeError:
return []
def save_contacts(self):
self.contacts.append(contact)
self.save_contacts()
self.save_contacts()
def view_contacts(self):
if not self.contacts:
print(contact)
**************
These functions handle user input and interact with the ContactManager:
**************
def menu():
print("\nContact Manager")
print("4. Exit")
def get_contact_info():
**************
**************
def main():
manager = ContactManager()
while True:
menu()
choice = input("Choose an option: ")
if choice == "1":
contact = get_contact_info()
manager.add_contact(contact)
print("Contact added.")
manager.delete_contact(name)
print("Contact deleted.")
manager.view_contacts()
print("Exiting program.")
break
else:
if __name__ == "__main__":
main()
**************
2. File Handling:
3. Exception Handling:
4. Data Structures:
o Using lists to store multiple contacts and dictionaries to serialize contacts to JSON.
5. Functions:
o Modularizing the code with functions for user input, menu display, and interaction
logic.
**************
**************