Question
Long python code
Answers
Answered by
GPT-4o mini
Certainly! Here’s an example of a longer Python program that implements a simple command-line address book. This program allows users to add, view, update, and delete contacts from their address book. It makes use of classes for better organization and functionality.
```python
import json
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
def to_dict(self):
return {
"name": self.name,
"phone": self.phone,
"email": self.email
}
@staticmethod
def from_dict(data):
return Contact(data['name'], data['phone'], data['email'])
class AddressBook:
def __init__(self, filename="address_book.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)
self.contacts = {name: Contact.from_dict(contact) for name, contact in data.items()}
except FileNotFoundError:
self.contacts = {}
except json.JSONDecodeError:
print("Error loading contacts. The file might be corrupted.")
self.contacts = {}
def save_contacts(self):
with open(self.filename, 'w') as file:
json.dump({name: contact.to_dict() for name, contact in self.contacts.items()}, file)
def add_contact(self, name, phone, email):
if name in self.contacts:
print(f"Contact '{name}' already exists.")
else:
self.contacts[name] = Contact(name, phone, email)
self.save_contacts()
print(f"Contact '{name}' added successfully.")
def view_contacts(self):
if not self.contacts:
print("No contacts available.")
else:
for name, contact in self.contacts.items():
print(f"Name: {name}, Phone: {contact.phone}, Email: {contact.email}")
def update_contact(self, name, phone=None, email=None):
if name not in self.contacts:
print(f"No contact found with the name '{name}'.")
return
if phone:
self.contacts[name].phone = phone
if email:
self.contacts[name].email = email
self.save_contacts()
print(f"Contact '{name}' updated successfully.")
def delete_contact(self, name):
if name in self.contacts:
del self.contacts[name]
self.save_contacts()
print(f"Contact '{name}' deleted successfully.")
else:
print(f"No contact found with the name '{name}'.")
def main():
address_book = AddressBook()
while True:
print("\nAddress Book Menu:")
print("1. Add Contact")
print("2. View Contacts")
print("3. Update Contact")
print("4. Delete Contact")
print("5. Exit")
choice = input("Choose an option: ")
if choice == '1':
name = input("Enter name: ")
phone = input("Enter phone: ")
email = input("Enter email: ")
address_book.add_contact(name, phone, email)
elif choice == '2':
address_book.view_contacts()
elif choice == '3':
name = input("Enter the name of the contact to update: ")
phone = input("Enter new phone (press enter to skip): ")
email = input("Enter new email (press enter to skip): ")
address_book.update_contact(name, phone if phone else None, email if email else None)
elif choice == '4':
name = input("Enter the name of the contact to delete: ")
address_book.delete_contact(name)
elif choice == '5':
print("Exiting the address book program.")
break
else:
print("Invalid choice. Please select a valid option.")
if __name__ == "__main__":
main()
```
### Code Overview:
1. **Contact Class**: Represents a single contact with attributes for name, phone, and email.
2. **AddressBook Class**: Handles the collection of contacts. It includes methods for adding, viewing, updating, deleting contacts and loading/saving the contacts from/to a JSON file.
3. **Main Function**: Provides a command-line interface for users to interact with their address book.
### Usage:
- You can run this program in a Python environment.
- It will prompt you with a menu to manage your contacts.
- All contacts are stored in a JSON file named `address_book.json`, so you can persist your data between sessions.
```python
import json
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
def to_dict(self):
return {
"name": self.name,
"phone": self.phone,
"email": self.email
}
@staticmethod
def from_dict(data):
return Contact(data['name'], data['phone'], data['email'])
class AddressBook:
def __init__(self, filename="address_book.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)
self.contacts = {name: Contact.from_dict(contact) for name, contact in data.items()}
except FileNotFoundError:
self.contacts = {}
except json.JSONDecodeError:
print("Error loading contacts. The file might be corrupted.")
self.contacts = {}
def save_contacts(self):
with open(self.filename, 'w') as file:
json.dump({name: contact.to_dict() for name, contact in self.contacts.items()}, file)
def add_contact(self, name, phone, email):
if name in self.contacts:
print(f"Contact '{name}' already exists.")
else:
self.contacts[name] = Contact(name, phone, email)
self.save_contacts()
print(f"Contact '{name}' added successfully.")
def view_contacts(self):
if not self.contacts:
print("No contacts available.")
else:
for name, contact in self.contacts.items():
print(f"Name: {name}, Phone: {contact.phone}, Email: {contact.email}")
def update_contact(self, name, phone=None, email=None):
if name not in self.contacts:
print(f"No contact found with the name '{name}'.")
return
if phone:
self.contacts[name].phone = phone
if email:
self.contacts[name].email = email
self.save_contacts()
print(f"Contact '{name}' updated successfully.")
def delete_contact(self, name):
if name in self.contacts:
del self.contacts[name]
self.save_contacts()
print(f"Contact '{name}' deleted successfully.")
else:
print(f"No contact found with the name '{name}'.")
def main():
address_book = AddressBook()
while True:
print("\nAddress Book Menu:")
print("1. Add Contact")
print("2. View Contacts")
print("3. Update Contact")
print("4. Delete Contact")
print("5. Exit")
choice = input("Choose an option: ")
if choice == '1':
name = input("Enter name: ")
phone = input("Enter phone: ")
email = input("Enter email: ")
address_book.add_contact(name, phone, email)
elif choice == '2':
address_book.view_contacts()
elif choice == '3':
name = input("Enter the name of the contact to update: ")
phone = input("Enter new phone (press enter to skip): ")
email = input("Enter new email (press enter to skip): ")
address_book.update_contact(name, phone if phone else None, email if email else None)
elif choice == '4':
name = input("Enter the name of the contact to delete: ")
address_book.delete_contact(name)
elif choice == '5':
print("Exiting the address book program.")
break
else:
print("Invalid choice. Please select a valid option.")
if __name__ == "__main__":
main()
```
### Code Overview:
1. **Contact Class**: Represents a single contact with attributes for name, phone, and email.
2. **AddressBook Class**: Handles the collection of contacts. It includes methods for adding, viewing, updating, deleting contacts and loading/saving the contacts from/to a JSON file.
3. **Main Function**: Provides a command-line interface for users to interact with their address book.
### Usage:
- You can run this program in a Python environment.
- It will prompt you with a menu to manage your contacts.
- All contacts are stored in a JSON file named `address_book.json`, so you can persist your data between sessions.