How to Build a Habit Tracker with Python: A Complete Step‑by‑Step Guide for Beginners

Building a habit tracker is one of the most rewarding projects you can undertake as a Python programmer. Not only does it help you understand core concepts like data structures, file I/O, and user input handling, but it also produces a tool you can actually use in your daily life. Whether you are trying to drink more water, exercise regularly, or read every day, a habit tracker gives you the visibility and accountability you need to form lasting habits. In this tutorial, we will walk through the complete process of creating a command‑line habit tracker written entirely in Python. The tracker will allow you to add habits, mark them as done for the day, view your streaks, and store data persistently so you never lose your progress. By the end of this article, you will have a fully functional habit tracker that you can extend and customise to fit your own routines. We will use only Python’s standard library – no external dependencies required – making it an accessible project for developers of any skill level.

Before we dive into the code, it helps to understand the core features a habit tracker should offer. At its heart, a habit tracker needs to let you define habits (e.g., “run for 20 minutes”), record completion for each habit on a given date, and compute simple statistics like the current streak (number of consecutive days completed). It also needs to save this data between sessions so that when you close your terminal and open it again the next morning, your progress is still there. We will implement persistence using a lightweight SQLite database, which comes bundled with Python. This gives us a robust, query‑friendly storage system without needing to install anything extra. We will also keep the user interface text‑based but clear, with menus and prompts that guide you through each action. The entire project will be built in under 300 lines of code, but we will explain every section in detail so that you can understand not just what the code does, but why it works that way.

Article illustration

Step‑by��Step Guide to Building Your Habit Tracker

We are going to build the habit tracker in six main steps: setting up the database, creating the data model, writing the core functions (add, check‑in, streaks), building the user menu, testing the application, and adding a few polish touches. Each step builds on the previous one, so follow along in order. You can copy the code snippets and run them in your own environment – we recommend using Python 3.8 or later.

Step 1: Set Up the SQLite Database

The first thing we need is a place to store our habits and their completion records. SQLite is a perfect choice: it is a file‑based relational database that requires no server process. We will create a single database file called habits.db and define two tables. The first table, habits, stores each habit’s unique ID, name, and creation date. The second table, completions, records every time a habit is marked as done – it holds a reference to the habit’s ID and the date of completion. Using a separate table for completions allows us to easily run queries that calculate streaks, count completions per month, etc. Below is the SQL code to create these tables. We will run it inside a Python function that gets called when the program starts.


-- habits table
CREATE TABLE IF NOT EXISTS habits (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    created_date TEXT NOT NULL
);

-- completions table
CREATE TABLE IF NOT EXISTS completions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    habit_id INTEGER NOT NULL,
    completion_date TEXT NOT NULL,
    FOREIGN KEY (habit_id) REFERENCES habits(id)
);

In your Python code, you will import sqlite3, connect to the database, and execute these two CREATE statements. Wrapping the connection in a with statement ensures it is properly closed even if an error occurs. We will also set the row_factory to sqlite3.Row so that we can access columns by name, which makes code more readable. Here is the complete initialisation function:


import sqlite3
from datetime import date, timedelta

DB_NAME = "habits.db"

def init_db():
    conn = sqlite3.connect(DB_NAME)
    conn.row_factory = sqlite3.Row
    c = conn.cursor()
    c.execute("""
        CREATE TABLE IF NOT EXISTS habits (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            created_date TEXT NOT NULL
        )
    """)
    c.execute("""
        CREATE TABLE IF NOT EXISTS completions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            habit_id INTEGER NOT NULL,
            completion_date TEXT NOT NULL,
            FOREIGN KEY (habit_id) REFERENCES habits(id)
        )
    """)
    conn.commit()
    conn.close()

Call init_db() exactly once at the start of your main function. If the database file already exists and the tables are present, SQLite will simply ignore the CREATE IF NOT EXISTS statements. This makes the code re‑runnable without destroying existing data.

Step 2: Define the Data Model and Helper Functions

Now that the database is ready, we need a way to interact with it. We will write functions that correspond to each user action: adding a new habit, checking off a habit for today, viewing all habits with their streaks, and deleting a habit. We will also need a helper function to get today’s date as a string in the format YYYY‑MM‑DD, because dates are stored as text in SQLite (SQLite has no native date type, but text comparisons work as long as the format is consistent).


def today_str():
    return date.today().isoformat()   # e.g., "2025-04-05"

def add_habit(name):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("INSERT INTO habits (name, created_date) VALUES (?, ?)", (name, today_str()))
    conn.commit()
    conn.close()
    print(f"Habit '{name}' added successfully.")

def get_all_habits():
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT id, name, created_date FROM habits ORDER BY created_date DESC")
    rows = c.fetchall()
    conn.close()
    return rows

The check_off_habit function is a bit more involved. First, it checks whether the user has already completed this habit today – we want to prevent duplicate entries. If the habit has not been completed today, we insert a new row into the completions table. We also need to consider what happens if the user misses a day: the streak should break. We will compute streaks later, but for now we just store the fact that the habit was done on a particular date.


def check_off_habit(habit_id):
    t = today_str()
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    # check for duplicate
    c.execute("""
        SELECT id FROM completions 
        WHERE habit_id = ? AND completion_date = ?
    """, (habit_id, t))
    if c.fetchone():
        print("You already checked off this habit today.")
        conn.close()
        return
    c.execute("INSERT INTO completions (habit_id, completion_date) VALUES (?, ?)", (habit_id, t))
    conn.commit()
    conn.close()
    print("Habit marked as done today.")

Step 3: Calculate Streaks – The Heart of the Tracker

Streaks are what make a habit tracker motivating. A streak is the number of consecutive days (including today) that a habit has been completed without missing a single day. To calculate it, we need to look at the completion dates for a given habit, sort them, and then count backwards from today until we hit a break. This is easier if we first generate a set of all dates we expect (from the creation date up to today) and check which ones have been completed. However, that can be slow for old habits. Instead, we can use a SQL query that gets all distinct completion dates in ascending order, then loop through them in reverse. The code below implements a robust streak calculation:


def get_streak(habit_id):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    # all completion dates for this habit, sorted ascending
    c.execute("""
        SELECT DISTINCT completion_date FROM completions
        WHERE habit_id = ?
        ORDER BY completion_date ASC
    """, (habit_id,))
    dates = [row["completion_date"] for row in c.fetchall()]
    conn.close()

    if not dates:
        return 0   # never completed

    # convert strings to date objects
    dates = [date.fromisoformat(d) for d in dates]
    # start from today and count backwards
    streak = 0
    current = date.today()
    # we'll create a set for O(1) lookups
    date_set = set(dates)
    while True:
        if current in date_set:
            streak += 1
            current -= timedelta(days=1)
        else:
            # if today hasn't been completed yet, the streak is 0 (unless we allow grace period)
            # but we want to count only if today is done.
            # If today is missing, the streak should be 0.
            # However, if the habit was just started today and completed, that's a streak of 1.
            break
    # But note: if today is not completed, we want streak = 0, because the user hasn't done it yet today.
    # Our loop above would break at first missing day (today itself), so streak = 0. Good.
    # But what if the last completion was yesterday? Then loop: today missing -> break, streak=0.
    # Actually, if today is missing but yesterday was done, we want streak = 0 because the habit is not continued today.
    # So the logic is correct: we start from today and need today to be present for any streak > 0.
    # However, if the user hasn't checked in today but did yesterday, we might want to show "0" or "1"? Usually it's 0.
    # Let's implement the standard: streak = number of consecutive days ending at yesterday if today not done.
    # More common: streak = days completed in a row as of the last completion. Let's refine.
    # Actually, many trackers show the current streak based on the most recent completion.
    # If today is not done, streak is 0 because the habit hasn't been done today.
    # But if you miss a day, streak resets. That's what we have.
    # However, if today is not done, but yesterday was done, streak = 1? No, because "current" means you have to do it today.
    # Let's change: compute streak from the most recent completion date backwards.
    # We'll take the most recent date, then count backwards from there.
    # If the most recent date is today, we count backwards until a break, giving streak >=1.
    # If the most recent date is yesterday, we count backwards from yesterday, giving streak >=1 but today not included.
    # This is more useful: the user sees "I have a streak of 5 days" meaning I did it the last 5 days (including maybe today).
    # We'll implement both? No, keep simple: streak based on today's status.
    # Many habit apps show "0" if you haven't done it today. Let's stick with that for clarity.
    return streak

Wait – the above code has a bug: if today is not completed, streak is 0 even if the user has done it for the past week. That is not very informative. A better approach: compute the streak from the most recent completion date (which could be yesterday) and show that. The user can then see “7‑day streak” even if they haven’t done it today yet. But then when they miss a day, the streak will be computed from the last completed day, which is fine. Let’s rewrite streak calculation to return the length of the consecutive chain ending at the last completed date (which may be earlier than today). To do this, we take the sorted list of dates, start from the last one, and count backwards as long as each previous date is exactly one day earlier. This is the classic approach.


def get_streak(habit_id):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("""
        SELECT DISTINCT completion_date FROM completions
        WHERE habit_id = ?
        ORDER BY completion_date DESC
    """, (habit_id,))
    dates = [row["completion_date"] for row in c.fetchall()]
    conn.close()
    if not dates:
        return 0
    # convert to date objects
    dates = [date.fromisoformat(d) for d in dates]
    streak = 1
    for i in range(1, len(dates)):
        if dates[i-1] - dates[i] == timedelta(days=1):
            streak += 1
        else:
            break
    return streak

This code assumes dates are in descending order. It starts with the most recent completion (date[0]), then checks if the next date is exactly one day before. It continues until the gap is not exactly one day. The result is the length of the consecutive run ending at the latest completion. This is the most intuitive “streak” displayed in apps like Duolingo. We will use this version.

Step 4: Build the User Menu and Main Loop

Now we need a way for the user to interact with our functions. A simple text menu with numbered options works well. The main loop will keep displaying the menu until the user chooses to exit. We will also display a list of all habits and their current streaks right on the main screen, so the user can see an overview without extra commands.


def show_menu():
    print("\n--- Habit Tracker ---")
    print("1. Add a new habit")
    print("2. Check off a habit for today")
    print("3. View all habits with streaks")
    print("4. Delete a habit")
    print("5. Exit")
    choice = input("Enter your choice (1-5): ").strip()
    return choice

def main():
    init_db()
    while True:
        choice = show_menu()
        if choice == '1':
            name = input("Enter habit name: ").strip()
            if name:
                add_habit(name)
            else:
                print("Name cannot be empty.")
        elif choice == '2':
            habits = get_all_habits()
            if not habits:
                print("No habits yet. Add one first.")
                continue
            print("\nYour habits:")
            for h in habits:
                streak = get_streak(h["id"])
                print(f"{h['id']}: {h['name']} (streak: {streak})")
            try:
                hid = int(input("Enter the ID of the habit to check off: "))
                check_off_habit(hid)
            except ValueError:
                print("Invalid ID.")
        elif choice == '3':
            habits = get_all_habits()
            if not habits:
                print("No habits defined.")
            else:
                print("\nHabit overview:")
                for h in habits:
                    streak = get_streak(h["id"])
                    print(f"- {h['name']}: {streak} day streak")
        elif choice == '4':
            habits = get_all_habits()
            if not habits:
                print("No habits to delete.")
                continue
            for h in habits:
                print(f"{h['id']}: {h['name']}")
            try:
                hid = int(input("Enter the ID of the habit to delete: "))
                delete_habit(hid)
            except ValueError:
                print("Invalid ID.")
        elif choice == '5':
            print("Goodbye! Keep building those habits.")
            break
        else:
            print("Invalid choice. Please enter 1-5.")

You will also need the delete_habit function, which removes the habit and all its completions:


def delete_habit(habit_id):
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("DELETE FROM completions WHERE habit_id = ?", (habit_id,))
    c.execute("DELETE FROM habits WHERE id = ?", (habit_id,))
    conn.commit()
    conn.close()
    print("Habit deleted.")

Step 5: Test and Refine the Application

Run your main() function and test each option. Add a habit, check it off several days (you can manually change your system date temporarily to simulate different days – but be careful not to corrupt real data). A better way to test is to write a small test script that inserts dates directly into the database. For example, you can use Python to insert completion dates for the past week and then call get_streak. This will help you verify that the streak calculation works as expected. Also test edge cases: what happens if you check off the same habit twice on the same day? Our code prints “already checked off.” What if you try to delete a non‑existent ID? The SQL will just delete nothing and you will get a message. You can improve error handling later.

At this point, the habit tracker is fully functional. However, a week‑long user might want a few quality‑of‑life features. For instance, the overview screen could show the last completion date, or you could add a “show longest streak” feature. You could also add a simple command‑line argument parser to let users run actions directly (e.g., python tracker.py add "Read 30 min"). But the core is solid. Let’s now talk about best practices for extending and maintaining this project.

Tips and Best Practices for Your Habit Tracker

Now that you have a working habit tracker, here are three advanced tips to make it more robust and useful.

Tip 1: Use Context Managers for Database Connections

In every function that interacts with the database, we open a connection and then close it manually. This works, but if an exception occurs between connect() and close(), the connection can be left open. A better pattern is to use a context manager, either by wrapping the connection in with (SQLite’s connection object does act as a context manager in Python 3.12+ – but to be safe, you can create a helper or use contextlib.closing). For example:


import contextlib

@contextlib.contextmanager
def get_db():
    conn = sqlite3.connect(DB_NAME)
    conn.row_factory = sqlite3.Row
    try:
        yield conn
    finally:
        conn.close()

Then inside each function you write with get_db() as conn: and perform all operations inside that block. This ensures the connection is always closed, even if the code raises an exception.

Tip 2: Add Data Validation and Error Recovery

User input is unpredictable. What if someone enters a habit name that is 1,000 characters long? Or tries to check off a habit that doesn’t exist? You should validate all inputs. For the habit name, enforce a maximum length (e.g., 100 characters) and trim whitespace. For habit IDs, check that the ID actually exists in the database before proceeding. You can write a helper function habit_exists(hid) that returns a boolean. Also consider adding a confirmation prompt before deleting a habit, to avoid accidental loss of data.

Tip 3: Keep Your Database Backed Up

Your habit data lives in habits.db. If something goes wrong (e.g., file corruption, accidental deletion), you could lose months of progress. The simplest backup solution is to regularly copy the file to another location. You can even add a small menu option that exports your data to a JSON file, which can be read by other programs. Here is a quick export function:


import json

def export_to_json():
    conn = sqlite3.connect(DB_NAME)
    c = conn.cursor()
    c.execute("SELECT * FROM habits")
    habits = [dict(row) for row in c.fetchall()]
    c.execute("SELECT * FROM completions")
    completions = [dict(row) for row in c.fetchall()]
    conn.close()
    data = {"habits": habits, "completions": completions}
    with open("habits_backup.json", "w") as f:
        json.dump(data, f, indent=2)
    print("Data exported to habits_backup.json")

Frequently Asked Questions (FAQ)

Q1: Can I run this habit tracker on a phone or tablet?
A: The tracker is designed for a terminal/command line, so it works best on a desktop or laptop. However, you can run it on Android using Termux (a Linux emulator for Android) or on iOS using Pythonista or a‑shell. The code is pure Python, so it will run anywhere Python is installed.

Q2: How do I change the streak calculation to not require today’s completion?
A: Our current streak calculation uses the most recent completion date (which could be yesterday). If you prefer the streak to show 0 when today is incomplete, modify the get_streak function to start counting from today and require today to be in the set. The original commented code in Step 3 shows that approach.

Q3: The database file is growing. Should I be worried?
A: SQLite databases are extremely compact. Even if you check off 10 habits every day for a decade, the database will be well under 1 MB. There is no need to worry about size. If you ever want to clear old data, you can add a “purge completions older than 1 year” function.

Q4: Can I add multiple users or sync across devices?
A: The current design uses a local file. To support multiple users, you would need to add a user table and modify every query to filter by user. For sync, consider using a remote SQLite database on a cloud drive (like Dropbox) but be careful about concurrent access. A better approach is to switch to a client‑server database like PostgreSQL, but that is overkill for a personal tracker.

Q5: Why did you use DISTINCT in the query for completions?
A: Our check_off_habit function prevents duplicate completions on the same day, but if you ever run a bulk import or manually insert data, duplicates could creep in. Using SELECT DISTINCT completion_date ensures that our streak calculation treats multiple completions on the same day as a single day. That is safer.

Q6: How can I see my longest streak ever?
A: You would need to examine all consecutive runs in the completion history. A simple way is to iterate over all dates in the completions table (after sorting) and keep track of the longest run. This is a bit more complex but doable. A future enhancement could add an option “Show longest streak” to the menu.

Database Schema Summary
Table Column Type Description
habits id INTEGER PRIMARY KEY Unique identifier for each habit
habits name TEXT NOT NULL Name of the habit (e.g., “Meditate 10 min”)
habits created_date TEXT NOT NULL Date the habit was created (ISO format)
completions id INTEGER PRIMARY KEY Unique identifier for each completion
completions habit_id INTEGER NOT NULL Foreign key referencing habits.id
completions completion_date TEXT NOT NULL Date when the habit was completed (ISO format)
Function Reference for the Habit Tracker
Function Purpose Parameters
init_db() Creates database tables if they don’t exist None
add_habit(name) Inserts a new habit into the database name (str)
check_off_habit(habit_id) Marks a habit as completed for today (if not already done) habit_id (int)
get_all_habits() Returns a list of all habits (as sqlite3.Row objects) None
get_streak(habit_id) Calculates the current consecutive day streak for a habit habit_id (int)
delete_habit(habit_id) Removes a habit and all its completions habit_id (int)

Conclusion

You have now built a fully functional habit tracker in Python that uses SQLite for persistence, calculates streaks, and provides an interactive command‑line interface. This project not only helps you keep track of your daily goals but also teaches you essential software development patterns: database design, CRUD operations, input validation, and separation of concerns. The entire codebase is under 200 lines, making it easy to understand and modify. You can extend it in countless ways: add a graphical interface with Tkinter or a web frontend with Flask, implement push notifications, or even turn it into a shared family habit tracker. The modular design we used means you can replace the CLI with a GUI without touching the database layer. As you continue to use your tracker, you will likely discover features you want to add – maybe a weekly report or a visual calendar. All those enhancements are now within your reach. The most important thing is that you have taken the first step: building something real and useful. Keep coding, keep tracking, and keep forming those good habits.

sarah antaboga
Author: sarah antaboga

Leave a Reply

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