Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Users can add a new expense by providing details such as date, category (e.g., groceries, transportation, entertainment), and amount spent. Delete Expense: Users can delete
- Users can add a new expense by providing details such as date, category (e.g., groceries, transportation, entertainment), and amount spent.
- Delete Expense: Users can delete an expense from the tracker by specifying the expense ID or date.
- Update Expense: Users can update the details (category or amount) of an existing expense.
- View Monthly Summary: Display a summary of expenses for a specific month, including total spending and category-wise breakdown.
- Export Data: Allow users to export their expense data to a CSV file for further analysis.
Requirements:
- Use classes and object-oriented programming to design the expense tracker.
- Implement error handling for cases such as invalid expense IDs or incorrect input.
- Store expense records in a list or dictionary within the program.
- class ExpenseTracker:
def __init__(self):
# Initialize an empty dictionary to store expense records
self.expenses = {}
def add_expense(self, date, category, amount):
"""
Add a new expense record to the tracker.
Args:
date (str): Date of the expense (e.g., "2024-04-15").
category (str): Category of the expense (e.g., "Groceries").
amount (float): Amount spent (positive value).
Returns:
None
"""
# Generate a unique expense ID (you can use a timestamp or a counter)
expense_id = len(self.expenses) + 1
# Create an expense record
expense = {
"date": date,
"category": category,
"amount": amount
}
# Add the record to the dictionary
self.expenses[expense_id] = expense
def delete_expense(self, expense_id):
"""
Delete an expense record from the tracker.
Args:
expense_id (int): ID of the expense to be deleted.
Returns:
None
"""
if expense_id in self.expenses:
del self.expenses[expense_id]
else:
print(f"Expense with ID {expense_id} not found.")
def update_expense(self, expense_id, category=None, amount=None):
"""
Update the details of an existing expense.
Args:
expense_id (int): ID of the expense to be updated.
category (str, optional): New category (if provided).
amount (float, optional): New amount (if provided).
Returns:
None
"""
if expense_id in self.expenses:
expense = self.expenses[expense_id]
if category:
expense["category"] = category
if amount:
expense["amount"] = amount
else:
print(f"Expense with ID {expense_id} not found.")
def view_monthly_summary(self, month, year):
"""
Display a summary of expenses for a specific month.
Args:
month (int): Month (1 to 12).
year (int): Year (e.g., 2024).
Returns:
None
"""
total_spending = 0
category_summary = {}
for expense in self.expenses.values():
expense_month, expense_year = map(int, expense["date"].split("-"))
if expense_month == month and expense_year == year:
total_spending += expense["amount"]
category = expense["category"]
category_summary.setdefault(category, 0)
category_summary[category] += expense["amount"]
print(f"Summary for {month}/{year}:")
print(f"Total spending: ${total_spending:.2f}")
for category, amount in category_summary.items():
print(f"{category}: ${amount:.2f}")
def export_to_csv(self, filename):
"""
Export expense data to a CSV
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started