Personal Expense Tracker

Personal Expense Tracker: A Python Program to Manage, Track, and Analyze Your Daily Spending Habits

Project Overview

The Personal Expense Tracker is a Python application designed to help individuals manage their expenses effectively. The project allows users to add, view, categorize, and track their expenses. With a simple command-line interface, users can enter details such as date, category, amount, and description for each expense. The program offers the ability to filter expenses by category, calculate total expenditures, and display a summary of expenses by category.

This project serves as a useful tool for anyone looking to better manage their finances, helping users keep track of their spending habits and providing insights into where their money is going.

Key Features

  • Add Expense: Allows users to enter a new expense by specifying the date, category, amount, and a brief description.
  • View Expenses: Displays all the recorded expenses in a tabular format.
  • Filter Expenses by Category: Enables users to filter and view expenses based on a specific category (e.g., Food, Entertainment, Utilities).
  • Calculate Total Expense: Computes the total amount of all recorded expenses.
  • Delete Expense: Allows users to delete an expense from the tracker by specifying its index.
  • Expense Summary: Displays a summary of total expenses for each category.

Flow of the Program

  • Initialization: The program starts by creating an instance of the ExpenseTracker class. This class contains an empty list of expenses, which is where all the expenses will be stored.
  • User Interaction: The program enters a loop, displaying a menu with options to the user. The options include adding an expense, viewing all expenses, filtering by category, calculating the total, deleting an expense, and viewing a summary.
  • Input Handling: Depending on the user’s choice, the program either adds a new expense, displays the expenses, filters them by category, or performs other tasks like calculating totals or deleting an expense. Each user action updates the list of expenses.
  • Displaying Results: The results of any action (e.g., list of expenses, total amount, summary) are displayed in a readable format, with headers for each column. This helps users easily interpret the data.
  • Exiting the Program: The program allows users to exit by selecting the corresponding menu option. Once exited, the program terminates gracefully.

Breaking Down the Code (Explain Code)

Let’s go step by step through the code to understand how the program works:

1. ExpenseTracker Class

This class is the core of the application, managing the expenses and providing various methods to interact with them.

  class ExpenseTracker:
    def __init__(self):
        self.expenses = []
  

  • __init__(self): The constructor initializes an empty list, self.expenses, where all expense data will be stored.

2. Add Expense Method

  def add_expense(self, date, category, amount, description):
    expense = {
        "date": date,
        "category": category,
        "amount": amount,
        "description": description,
    }
    self.expenses.append(expense)
  

  • add_expense(self, date, category, amount, description): This method adds a new expense to the tracker. It takes in details like date, category, amount, and description, and then stores them as a dictionary in the self.expenses list.

3. View Expenses Method

  def view_expenses(self):
    if not self.expenses:
        print("No expenses recorded.")
        return
    print("\nAll Expenses:")
    print("-" * 50)
    print(f"{'Date':<15}{'Category':<15}{'Amount':<10}{'Description'}")
    print("-" * 50)
    for expense in self.expenses:
        print(
            f"{expense['date']:<15}{expense['category']:<15}{expense['amount']:<10}{expense['description']}"
        )
    print("-" * 50)
  

  • view_expenses(self): This method displays all the recorded expenses. It first checks if there are any expenses. If there are none, it prints a message saying "No expenses recorded." Otherwise, it prints the expenses in a formatted table.

4. Filter Expenses by Category Method

  def filter_expenses_by_category(self, category):
    filtered = [exp for exp in self.expenses if exp["category"] == category]
    if not filtered:
        print(f"No expenses found for category '{category}'.")
        return
    print(f"\nExpenses in Category: {category}")
    print("-" * 50)
    print(f"{'Date':<15}{'Amount':<10}{'Description'}")
    print("-" * 50)
    for expense in filtered:
        print(
            f"{expense['date']:<15}{expense['amount']:<10}{expense['description']}"
        )
    print("-" * 50)
  

  • filter_expenses_by_category(self, category): This method filters the expenses by category. If there are no expenses for the specified category, it prints a message. If there are matching expenses, it displays them in a formatted table.

5. Calculate Total Expense Method

  def calculate_total_expense(self):
    total = sum(expense["amount"] for expense in self.expenses)
    return total
  

  • calculate_total_expense(self): This method calculates the total of all recorded expenses by summing the amount field of each expense. It returns the total.

6. Delete Expense Method

  def delete_expense(self, index):
    if 0 <= index < len(self.expenses):
        deleted = self.expenses.pop(index)
        print(f"Deleted expense: {deleted}")
    else:
        print("Invalid index. No expense deleted.")
  

  • delete_expense(self, index): This method allows the user to delete an expense by its index in the list. If the index is valid, the expense is removed using the pop() method, and a message is displayed. If the index is invalid, an error message is shown.

7. Display Summary Method

  def display_summary(self):
    if not self.expenses:
        print("No expenses recorded.")
        return
    summary = {}
    for expense in self.expenses:
        category = expense["category"]
        amount = expense["amount"]
        summary[category] = summary.get(category, 0) + amount
    print("\nExpense Summary by Category:")
    print("-" * 50)
    print(f"{'Category':<20}{'Total Amount'}")
    print("-" * 50)
    for category, total in summary.items():
        print(f"{category:<20}{total}")
    print("-" * 50)
  

  • display_summary(self): This method generates a summary of expenses by category. It sums the amounts for each category and then prints a table showing the category name and the total expense for that category.

Final Code

Here is the complete code for the Personal Expense Tracker

  # Personal Expense Tracker

class ExpenseTracker:
    def __init__(self):
        self.expenses = []

    def add_expense(self, date, category, amount, description):
        """Add an expense to the tracker."""
        expense = {
            "date": date,
            "category": category,
            "amount": amount,
            "description": description,
        }
        self.expenses.append(expense)

    def view_expenses(self):
        """Display all recorded expenses."""
        if not self.expenses:
            print("No expenses recorded.")
            return

        print("\nAll Expenses:")
        print("-" * 50)
        print(f"{'Date':<15}{'Category':<15}{'Amount':<10}{'Description'}")
        print("-" * 50)
        for expense in self.expenses:
            print(
                f"{expense['date']:<15}{expense['category']:<15}{expense['amount']:<10}{expense['description']}"
            )
        print("-" * 50)

    def filter_expenses_by_category(self, category):
        """Filter expenses by a specific category."""
        filtered = [exp for exp in self.expenses if exp["category"] == category]

        if not filtered:
            print(f"No expenses found for category '{category}'.")
            return

        print(f"\nExpenses in Category: {category}")
        print("-" * 50)
        print(f"{'Date':<15}{'Amount':<10}{'Description'}")
        print("-" * 50)
        for expense in filtered:
            print(
                f"{expense['date']:<15}{expense['amount']:<10}{expense['description']}"
            )
        print("-" * 50)

    def calculate_total_expense(self):
        """Calculate and return the total expense."""
        total = sum(expense["amount"] for expense in self.expenses)
        return total

    def delete_expense(self, index):
        """Delete an expense by its index."""
        if 0 <= index < len(self.expenses):
            deleted = self.expenses.pop(index)
            print(f"Deleted expense: {deleted}")
        else:
            print("Invalid index. No expense deleted.")

    def display_summary(self):
        """Display a summary of expenses by category."""
        if not self.expenses:
            print("No expenses recorded.")
            return

        summary = {}
        for expense in self.expenses:
            category = expense["category"]
            amount = expense["amount"]
            summary[category] = summary.get(category, 0) + amount

        print("\nExpense Summary by Category:")
        print("-" * 50)
        print(f"{'Category':<20}{'Total Amount'}")
        print("-" * 50)
        for category, total in summary.items():
            print(f"{category:<20}{total}")
        print("-" * 50)


def main():
    tracker = ExpenseTracker()

    while True:
        print("\n--- Personal Expense Tracker ---")
        print("1. Add Expense")
        print("2. View All Expenses")
        print("3. Filter Expenses by Category")
        print("4. Calculate Total Expense")
        print("5. Delete an Expense")
        print("6. Display Expense Summary")
        print("7. Exit")
        choice = input("Choose an option (1-7): ")

        if choice == "1":
            date = input("Enter the date (YYYY-MM-DD): ")
            category = input("Enter the category: ")
            amount = float(input("Enter the amount: "))
            description = input("Enter a brief description: ")
            tracker.add_expense(date, category, amount, description)
            print("Expense added successfully!")

        elif choice == "2":
            tracker.view_expenses()

        elif choice == "3":
            category = input("Enter the category to filter by: ")
            tracker.filter_expenses_by_category(category)

        elif choice == "4":
            total = tracker.calculate_total_expense()
            print(f"\nTotal Expense: {total}")

        elif choice == "5":
            tracker.view_expenses()
            index = int(input("Enter the index of the expense to delete (0-based): "))
            tracker.delete_expense(index)

        elif choice == "6":
            tracker.display_summary()

        elif choice == "7":
            print("Exiting the tracker. Goodbye!")
            break

        else:
            print("Invalid choice. Please select a valid option.")


if __name__ == "__main__":
    main()
  

sample output

Personal Expense Tracker by python 01
Personal Expense Tracker by python 02
Personal Expense Tracker by python 03

Let’s say a user chooses option 1 to add an expense. They enter the following information: Date: 2024-12-05 Category: Food Amount: 50.75 Description: Lunch After this, the expense is added to the tracker, and the user can choose option 2 to view all expenses, which will display: All Expenses: -------------------------------------------------- Date Category Amount Description -------------------------------------------------- 2024-12-05 Food 50.75 Lunch -------------------------------------------------- If the user chooses option 4, they can see the total expense: Total Expense: 50.75 If the user then chooses option 3 to filter expenses by the category Food, the program will display: Expenses in Category: Food -------------------------------------------------- Date Amount Description -------------------------------------------------- 2024-12-05 50.75 Lunch --------------------------------------------------

Conclusion

This Personal Expense Tracker is a simple yet effective Python program for managing personal finances. By allowing users to track, categorize, and calculate their expenses, the application offers a way to gain insights into spending habits. The program is easily extensible and could be enhanced with additional features such as exporting data to a file or incorporating a user-friendly graphical interface.

This project is ideal for beginners learning Python and object-oriented programming, as it involves working with classes, methods, lists, and basic input/output operations. By completing this project, users will gain hands-on experience with practical Python concepts and have a useful tool for managing their finances.

End of Post

Leave a Reply

Your email address will not be published. Required fields are marked *