Let's create a more complex example that demonstrates a variety of Python concepts.
We'll build a
simple contact management system that covers several key topics:
1. Classes and Objects (OOP)
2. File Handling
3. Exception Handling
4. Data Structures (Lists, Dictionaries)
5. Functions
6. Basic User Input and Output
Contact Management System
This system allows users to add, view, and delete contacts. Contacts are stored in a file, and the
program will handle errors gracefully.
1. Define the Contact Class
We'll create a class to represent a contact:
**************
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
def __str__(self):
return f"Name: {self.name}, Phone: {self.phone}, Email: {self.email}"
**************
2. Define the ContactManager Class
This class will manage the contacts, including loading from and saving to a file:
**************
import json
class ContactManager:
def __init__(self, filename="contacts.json"):
self.filename = filename
self.contacts = self.load_contacts()
def load_contacts(self):
try:
with open(self.filename, "r") as file:
data = json.load(file)
return [Contact(**item) for item in data]
except FileNotFoundError:
return []
except json.JSONDecodeError:
print("Error: The contact file is corrupted.")
return []
def save_contacts(self):
with open(self.filename, "w") as file:
json.dump([contact.__dict__ for contact in self.contacts], file)
def add_contact(self, contact):
self.contacts.append(contact)
self.save_contacts()
def delete_contact(self, name):
self.contacts = [contact for contact in self.contacts if contact.name != name]
self.save_contacts()
def view_contacts(self):
if not self.contacts:
print("No contacts found.")
for contact in self.contacts:
print(contact)
**************
3. Define Functions for User Interaction
These functions handle user input and interact with the ContactManager:
**************
def menu():
print("\nContact Manager")
print("1. Add Contact")
print("2. Delete Contact")
print("3. View Contacts")
print("4. Exit")
def get_contact_info():
name = input("Enter contact name: ")
phone = input("Enter contact phone: ")
email = input("Enter contact email: ")
return Contact(name, phone, email)
**************
4. Main Program Loop
This loop allows users to interact with the contact manager:
**************
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.")
elif choice == "2":
name = input("Enter the name of the contact to delete: ")
manager.delete_contact(name)
print("Contact deleted.")
elif choice == "3":
manager.view_contacts()
elif choice == "4":
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
**************
Key Concepts Covered
1. Classes and Objects (OOP):
o Contact and ContactManager classes encapsulate data and behaviors.
2. File Handling:
o Reading from and writing to a JSON file to persist contact data.
3. Exception Handling:
o Handling FileNotFoundError and json.JSONDecodeError when loading contacts.
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.
6. User Input and Output:
o Reading user input from the console and displaying output.
**************
**************