Day 30: Final Project: Calculator App

Objective

Create a complete program that combines multiple concepts from the challenge, including control flow, loops, file handling, user input, data structures, and problem-solving skills. This final project will give you hands-on experience building a more complex and useful application.

Project Idea: Budget Tracker
A simple program to track expenses and income, calculate balances, and save transaction history to a file.


Features of the Budget Tracker

  1. Add a Transaction:
    • Type: Income or Expense
    • Amount and description.
  2. View Transactions:
    • Show all transactions with details.
  3. Calculate Balance:
    • Display the total income, total expenses, and current balance.
  4. Save to File:
    • Save all transactions to a file for future reference.
  5. Load from File:
    • Reload saved transactions when the program starts.

Steps to Solve

1. Plan Your Solution

  1. Start by creating a menu for the user to interact with the program.
  2. Use a list or dictionary to store transactions with details (e.g., type, amount, and description).
  3. Write functions for each feature:
    • Adding transactions.
    • Displaying transactions.
    • Calculating and displaying the balance.
    • Saving to and loading from a file.
  4. Ensure the program runs in a loop until the user chooses to exit.

2. Code Examples

Python Example

import os

FILE_NAME = "transactions.txt"

def load_transactions():
    """Load transactions from the file."""
    if not os.path.exists(FILE_NAME):
        return []
    with open(FILE_NAME, "r") as file:
        transactions = [line.strip().split(",") for line in file.readlines()]
    return [{"type": t[0], "amount": float(t[1]), "description": t[2]} for t in transactions]

def save_transactions(transactions):
    """Save transactions to the file."""
    with open(FILE_NAME, "w") as file:
        for t in transactions:
            file.write(f"{t['type']},{t['amount']},{t['description']}\n")

def add_transaction(transactions):
    """Add a new transaction."""
    t_type = input("Enter transaction type (income/expense): ").lower()
    if t_type not in ["income", "expense"]:
        print("Invalid type! Please enter 'income' or 'expense'.")
        return
    try:
        amount = float(input("Enter the amount: "))
        description = input("Enter a description: ")
        transactions.append({"type": t_type, "amount": amount, "description": description})
        print("Transaction added!")
    except ValueError:
        print("Invalid amount! Please enter a number.")

def view_transactions(transactions):
    """Display all transactions."""
    if not transactions:
        print("No transactions found.")
        return
    print("\nTransactions:")
    for i, t in enumerate(transactions, start=1):
        print(f"{i}. {t['type'].capitalize()} - ${t['amount']:.2f} ({t['description']})")

def calculate_balance(transactions):
    """Calculate and display the balance."""
    income = sum(t['amount'] for t in transactions if t['type'] == "income")
    expense = sum(t['amount'] for t in transactions if t['type'] == "expense")
    balance = income - expense
    print("\nSummary:")
    print(f"Total Income: ${income:.2f}")
    print(f"Total Expenses: ${expense:.2f}")
    print(f"Balance: ${balance:.2f}")

def main():
    transactions = load_transactions()
    print("Welcome to the Budget Tracker!")
    
    while True:
        print("\nMenu:")
        print("1. Add a transaction")
        print("2. View transactions")
        print("3. Calculate balance")
        print("4. Save and Exit")
        choice = input("Enter your choice: ")

        if choice == "1":
            add_transaction(transactions)
        elif choice == "2":
            view_transactions(transactions)
        elif choice == "3":
            calculate_balance(transactions)
        elif choice == "4":
            save_transactions(transactions)
            print("Transactions saved. Goodbye!")
            break
        else:
            print("Invalid choice! Please try again.")

main()

JavaScript Example

const fs = require("fs");

const FILE_NAME = "transactions.json";

function loadTransactions() {
    if (!fs.existsSync(FILE_NAME)) {
        return [];
    }
    const data = fs.readFileSync(FILE_NAME, "utf8");
    return JSON.parse(data);
}

function saveTransactions(transactions) {
    fs.writeFileSync(FILE_NAME, JSON.stringify(transactions, null, 2));
    console.log("Transactions saved!");
}

function addTransaction(transactions) {
    const type = prompt("Enter transaction type (income/expense): ").toLowerCase();
    if (type !== "income" && type !== "expense") {
        console.log("Invalid type! Please enter 'income' or 'expense'.");
        return;
    }
    const amount = parseFloat(prompt("Enter the amount: "));
    if (isNaN(amount)) {
        console.log("Invalid amount! Please enter a number.");
        return;
    }
    const description = prompt("Enter a description: ");
    transactions.push({ type, amount, description });
    console.log("Transaction added!");
}

function viewTransactions(transactions) {
    if (transactions.length === 0) {
        console.log("No transactions found.");
        return;
    }
    console.log("\nTransactions:");
    transactions.forEach((t, index) => {
        console.log(`${index + 1}. ${t.type} - $${t.amount.toFixed(2)} (${t.description})`);
    });
}

function calculateBalance(transactions) {
    const income = transactions
        .filter(t => t.type === "income")
        .reduce((sum, t) => sum + t.amount, 0);
    const expense = transactions
        .filter(t => t.type === "expense")
        .reduce((sum, t) => sum + t.amount, 0);
    const balance = income - expense;
    console.log("\nSummary:");
    console.log(`Total Income: $${income.toFixed(2)}`);
    console.log(`Total Expenses: $${expense.toFixed(2)}`);
    console.log(`Balance: $${balance.toFixed(2)}`);
}

function main() {
    const transactions = loadTransactions();
    console.log("Welcome to the Budget Tracker!");

    while (true) {
        console.log("\nMenu:");
        console.log("1. Add a transaction");
        console.log("2. View transactions");
        console.log("3. Calculate balance");
        console.log("4. Save and Exit");
        const choice = prompt("Enter your choice: ");

        switch (choice) {
            case "1":
                addTransaction(transactions);
                break;
            case "2":
                viewTransactions(transactions);
                break;
            case "3":
                calculateBalance(transactions);
                break;
            case "4":
                saveTransactions(transactions);
                console.log("Goodbye!");
                return;
            default:
                console.log("Invalid choice! Please try again.");
        }
    }
}

main();

Final Reflections

This project brings together all the skills you’ve learned over the past 30 days, including:

  1. User interaction with menus and prompts.
  2. File handling to save and load data.
  3. Control flow and loops for program logic.
  4. Data structures for managing information.