How to Build Your First Python Project Step by Step (2026)

How to Build Your First Python Project Step by Step (2026)

Every beginner programmer faces the same problem.

You finish tutorials. You understand the concepts. But when you sit down to build something yourself — your mind goes completely blank.

This guide will walk you through building your first real Python project from scratch — step by step — no blanks, no confusion.

Let's get started.


1. Why Building Projects is Important

ReasonDetails
Solidifies learning   Concepts become real when you build
Portfolio building   Projects get you jobs and clients
Problem solving   Learn to think like a developer
Confidence building   Finishing a project feels incredible
Real world skills   Tutorials don't teach everything
Interview preparation   Companies ask about your projects

The truth: You learn more from one project than ten tutorials.


2. The Project We Will Build

Project: Personal Expense Tracker

This is the perfect first project because:

  • Practical and useful in real life
  • Covers all Python fundamentals
  • Not too complex but not too simple
  • Great for portfolio
  • Expandable later

What our expense tracker will do:

  • Add new expenses
  • View all expenses
  • Calculate total spending
  • Filter by category
  • Save data to file
  • Load data on startup

3. Skills You Need Before Starting

SkillLevel Needed
Variables and data types   Basic
Lists and dictionaries   Basic
Functions   Basic
Loops   Basic
File handling    Basic
User input   Basic

If you know these basics you are ready. ✅


4. Plan Before You Code

Never start coding without a plan. This is the biggest mistake beginners make.

Step 1 — Define what the program does:

  • Add expense with name, amount, category and date
  • View all expenses in a list
  • Calculate total expenses
  • Filter expenses by category
  • Save expenses to a file
  • Load expenses when program starts

Step 2 — Plan the data structure:

Each expense will be a dictionary:

python:

expense = {
    "name": "Lunch",
    "amount": 150.0,
    "category": "Food",
    "date": "2026-01-15"
}

All expenses stored in a list:

python:

expenses = [expense1, expense2, expense3]

Step 3 — Plan the functions:

  • add_expense()
  • view_expenses()
  • total_expenses()
  • filter_by_category()
  • save_expenses()
  • load_expenses()

5. Set Up Your Project

Create project folder structure

expense_tracker/

│
├── main.py
├── expenses.json
└── README.md

Open VS Code

  1. Create new folder called expense_tracker
  2. Open folder in VS Code
  3. Create main.py file

6. Build the Project Step by Step

Step 1 — Import required modules 

python:

import json
import os
from datetime import date

Step 2 — Create the data file handler

python:

EXPENSES_FILE = "expenses.json"

def load_expenses():
    """Load expenses from JSON file"""
    if os.path.exists(EXPENSES_FILE):
        with open(EXPENSES_FILE, "r") as file:
            return json.load(file)
    return []

def save_expenses(expenses):
    """Save expenses to JSON file"""
    with open(EXPENSES_FILE, "w") as file:
        json.dump(expenses, file, indent=4)
    print("Expenses saved successfully.")

Step 3 — Build the add expense function

python:

def add_expense(expenses):
    """Add a new expense"""
    print("\n--- Add New Expense ---")

    name = input("Expense name: ").strip()
    if not name:
        print("Expense name cannot be empty.")
        return

    try:
        amount = float(input("Amount (₹): "))
        if amount <= 0:
            print("Amount must be positive.")
            return
    except ValueError:
        print("Invalid amount. Please enter a number.")
        return

    print("\nCategories: Food, Transport, Shopping, Bills, Entertainment, Health, Other")
    category = input("Category: ").strip().title()
    if not category:
        category = "Other"

    expense_date = str(date.today())

    expense = {
        "name": name,
        "amount": amount,
        "category": category,
        "date": expense_date
    }

    expenses.append(expense)
    save_expenses(expenses)
    print(f"\n✅ Expense '{name}' of ₹{amount} added successfully!")

Step 4 — Build the view expenses function

python:

def view_expenses(expenses):
    """Display all expenses"""
    print("\n--- All Expenses ---")

    if not expenses:
        print("No expenses found. Start adding some!")
        return

    print(f"\n{'No.':<5} {'Name':<20} {'Amount':<12} {'Category':<15} {'Date'}")
    print("-" * 65)

    for i, expense in enumerate(expenses, 1):
        print(f"{i:<5} {expense['name']:<20} ₹{expense['amount']:<11.2f} {expense['category']:<15} {expense['date']}")

    print("-" * 65)
    print(f"Total: ₹{sum(e['amount'] for e in expenses):.2f}")

Step 5 — Build the total expenses function

python:

def total_expenses(expenses):
    """Calculate and display total expenses"""
    print("\n--- Expense Summary ---")

    if not expenses:
        print("No expenses to summarize.")
        return

    total = sum(expense["amount"] for expense in expenses)

    # Group by category
    categories = {}
    for expense in expenses:
        cat = expense["category"]
        if cat in categories:
            categories[cat] += expense["amount"]
        else:
            categories[cat] = expense["amount"]

    print(f"\n{'Category':<20} {'Amount':<12} {'Percentage'}")
    print("-" * 45)

    for category, amount in sorted(categories.items()):
        percentage = (amount / total) * 100
        print(f"{category:<20} ₹{amount:<11.2f} {percentage:.1f}%")

    print("-" * 45)
    print(f"{'TOTAL':<20} ₹{total:.2f}")
    print(f"\nTotal expenses: ₹{total:.2f}")
    print(f"Number of transactions: {len(expenses)}")
    print(f"Average per transaction: ₹{total/len(expenses):.2f}")

Step 6 — Build the filter by category function

python:

def filter_by_category(expenses):
    """Filter expenses by category"""
    print("\n--- Filter by Category ---")

    if not expenses:
        print("No expenses found.")
        return

    # Show available categories
    categories = list(set(expense["category"] for expense in expenses))
    print("Available categories:", ", ".join(categories))

    category = input("\nEnter category to filter: ").strip().title()

    filtered = [e for e in expenses if e["category"] == category]

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

    print(f"\n--- {category} Expenses ---")
    print(f"\n{'No.':<5} {'Name':<20} {'Amount':<12} {'Date'}")
    print("-" * 45)

    for i, expense in enumerate(filtered, 1):
        print(f"{i:<5} {expense['name']:<20} ₹{expense['amount']:<11.2f} {expense['date']}")

    print("-" * 45)
    print(f"Total {category} expenses: ₹{sum(e['amount'] for e in filtered):.2f}")

Step 7 — Build the delete expense function

python:

def delete_expense(expenses):
    """Delete an expense"""
    print("\n--- Delete Expense ---")

    if not expenses:
        print("No expenses to delete.")
        return

    view_expenses(expenses)

    try:
        index = int(input("\nEnter expense number to delete: ")) - 1
        if 0 <= index < len(expenses):
            deleted = expenses.pop(index)
            save_expenses(expenses)
            print(f"\n✅ Expense '{deleted['name']}' deleted successfully!")
        else:
            print("Invalid expense number.")
    except ValueError:
        print("Please enter a valid number.")

Step 8 — Build the main men

python:

def display_menu():
    """Display the main menu"""
    print("\n" + "="*40)
    print("    PERSONAL EXPENSE TRACKER")
    print("="*40)
    print("1. Add Expense")
    print("2. View All Expenses")
    print("3. Expense Summary")
    print("4. Filter by Category")
    print("5. Delete Expense")
    print("6. Exit")
    print("="*40)

def main():
    """Main function to run the expense tracker"""
    print("\nWelcome to Personal Expense Tracker!")

    # Load existing expenses
    expenses = load_expenses()
    print(f"Loaded {len(expenses)} existing expenses.")

    while True:
        display_menu()

        choice = input("\nEnter your choice (1-6): ").strip()

        if choice == "1":
            add_expense(expenses)
        elif choice == "2":
            view_expenses(expenses)
        elif choice == "3":
            total_expenses(expenses)
        elif choice == "4":
            filter_by_category(expenses)
        elif choice == "5":
            delete_expense(expenses)
        elif choice == "6":
            print("\nThank you for using Expense Tracker. Goodbye!")
            break
        else:
            print("\nInvalid choice. Please enter 1-6.")

if __name__ == "__main__":
    main()

7. Complete Final Code

Here is the complete project in one file:

python:

import json
import os
from datetime import date

EXPENSES_FILE = "expenses.json"

def load_expenses():
    if os.path.exists(EXPENSES_FILE):
        with open(EXPENSES_FILE, "r") as file:
            return json.load(file)
    return []

def save_expenses(expenses):
    with open(EXPENSES_FILE, "w") as file:
        json.dump(expenses, file, indent=4)

def add_expense(expenses):
    print("\n--- Add New Expense ---")
    name = input("Expense name: ").strip()
    if not name:
        print("Name cannot be empty.")
        return
    try:
        amount = float(input("Amount (₹): "))
        if amount <= 0:
            print("Amount must be positive.")
            return
    except ValueError:
        print("Invalid amount.")
        return
    print("Categories: Food, Transport, Shopping, Bills, Entertainment, Health, Other")
    category = input("Category: ").strip().title() or "Other"
    expense = {
        "name": name,
        "amount": amount,
        "category": category,
        "date": str(date.today())
    }
    expenses.append(expense)
    save_expenses(expenses)
    print(f"✅ Added: {name} - ₹{amount}")

def view_expenses(expenses):
    print("\n--- All Expenses ---")
    if not expenses:
        print("No expenses found.")
        return
    print(f"\n{'No.':<5} {'Name':<20} {'Amount':<12} {'Category':<15} {'Date'}")
    print("-" * 65)
    for i, e in enumerate(expenses, 1):
        print(f"{i:<5} {e['name']:<20} ₹{e['amount']:<11.2f} {e['category']:<15} {e['date']}")
    print("-" * 65)
    print(f"Total: ₹{sum(e['amount'] for e in expenses):.2f}")

def total_expenses(expenses):
    if not expenses:
        print("No expenses found.")
        return
    total = sum(e["amount"] for e in expenses)
    categories = {}
    for e in expenses:
        categories[e["category"]] = categories.get(e["category"], 0) + e["amount"]
    print("\n--- Summary ---")
    for cat, amt in sorted(categories.items()):
        print(f"{cat:<20} ₹{amt:.2f} ({amt/total*100:.1f}%)")
    print(f"\nTotal: ₹{total:.2f}")

def filter_by_category(expenses):
    if not expenses:
        print("No expenses found.")
        return
    categories = list(set(e["category"] for e in expenses))
    print("Categories:", ", ".join(categories))
    category = input("Enter category: ").strip().title()
    filtered = [e for e in expenses if e["category"] == category]
    if not filtered:
        print(f"No expenses in '{category}'")
        return
    for i, e in enumerate(filtered, 1):
        print(f"{i}. {e['name']} - ₹{e['amount']} ({e['date']})")
    print(f"Total: ₹{sum(e['amount'] for e in filtered):.2f}")

def delete_expense(expenses):
    if not expenses:
        print("No expenses to delete.")
        return
    view_expenses(expenses)
    try:
        index = int(input("Enter number to delete: ")) - 1
        if 0 <= index < len(expenses):
            deleted = expenses.pop(index)
            save_expenses(expenses)
            print(f"✅ Deleted: {deleted['name']}")
        else:
            print("Invalid number.")
    except ValueError:
        print("Enter a valid number.")

def display_menu():
    print("\n" + "="*40)
    print("    PERSONAL EXPENSE TRACKER")
    print("="*40)
    print("1. Add Expense")
    print("2. View All Expenses")
    print("3. Expense Summary")
    print("4. Filter by Category")
    print("5. Delete Expense")
    print("6. Exit")
    print("="*40)

def main():
    expenses = load_expenses()
    print(f"Welcome! Loaded {len(expenses)} expenses.")
    while True:
        display_menu()
        choice = input("Enter choice (1-6): ").strip()
        if choice == "1":
            add_expense(expenses)
        elif choice == "2":
            view_expenses(expenses)
        elif choice == "3":
            total_expenses(expenses)
        elif choice == "4":
            filter_by_category(expenses)
        elif choice == "5":
            delete_expense(expenses)
        elif choice == "6":
            print("Goodbye!")
            break
        else:
            print("Invalid choice. Enter 1-6.")

if __name__ == "__main__":
    main()

8. How to Run the Project

bash:

# Navigate to project folder
cd expense_tracker

# Run the program
python main.py

9. What You Learned Building This Project

ConceptWhere Used
Functions   Every feature is a function
Lists   Storing all expenses
Dictionaries   Each expense is a dictionary
Loops   Displaying and filtering expenses
File handling   Saving and loading JSON
Error handling   Input validation throughout
String formatting   Display table formatting
List comprehension   Filtering by category
Date module   Getting today's date
OS module   Checking if file exists

10. How to Improve This Project

Once you finish the basic version try adding these features:

Level 1 Improvements

  • Add monthly budget limit
  • Show warning when budget exceeded
  • Add expense editing feature
  • Search expenses by name

Level 2 Improvements

  • Add data visualization with matplotlib
  • Export data to Excel using openpyxl
  • Add recurring expenses feature
  • Monthly and yearly reports

Level 3 Improvements

  • Build a web version using Flask
  • Add user authentication
  • Build a mobile friendly interface
  • Connect to a real database

11. Push Your Project to GitHub

After finishing always push to GitHub:

bash:

git init
git add .
git commit -m "Add Personal Expense Tracker project"
git remote add origin https://github.com/yourusername/expense-tracker.git
git push origin main

Final Words

You just built your first real Python project. That is a massive achievement.

What you proved today:

  • You can plan a project
  • You can break problems into functions
  • You can handle user input and errors
  • You can work with files and data
  • You can build something useful

Your next steps:

  1. Add at least two improvements from the list above
  2. Push the project to GitHub
  3. Write a good README for it
  4. Share it on LinkedIn
  5. Start planning your next project

Every great developer started exactly where you are right now.

Keep learning. Keep building. 🚀


Follow CodeMindset on Pinterest for Python projects, coding guides and programming tutorials.


Comments

Popular posts from this blog

Best Laptops for Programming Students in India 2026

How to Use GitHub Complete Beginner Guide (2026)

Best Study System for Students in 2026 (Study Smarter Not Harder)