Sub topic 1
Tracking a Habit with a Simple Habit Tracker
Prerequisites
You should know basic Python functions, dictionaries, sets, loops, and the datetime module. You should also know how to read and write text files.
What makes a habit trackable
A trackable habit has a clear action and a clear completion rule. The tracker should answer one question with yes or no: “Did I do this today?”
“Read” is too vague. “Read for 20 minutes” is measurable. “Exercise” could become “walk for 30 minutes.” A useful habit also has a time boundary, such as a calendar day, so each check-in belongs to one period.
Avoid recording partial progress in the first version. A boolean check-in keeps the data model simple. You can add quantities later if the question changes to “How much did I do?”
Modeling check-ins as dates
Store each habit in a dictionary. The habit name is the key, and its value is a set of date objects. A set is useful because it contains each date at most once. Repeated check-ins are therefore idempotent: applying the same check-in again does not change the result.
from datetime import date
log = {
"read": {date(2026, 11, 25), date(2026, 11, 26)}
}
def check_in(habit, day=None):
day = day or date.today()
log.setdefault(habit, set()).add(day)
check_in("read", date(2026, 11, 26))
check_in("read", date(2026, 11, 27))
print(sorted(log["read"]))The date set is the source data. Streaks and completion rates should be calculated from it rather than stored separately. This prevents derived values from becoming inconsistent.
Recording a check-in
setdefault creates an empty set when the habit is new. The add method then records the date. Passing a date explicitly makes the function easy to test; omitting it records today.
Exercise
What happens when checkin("read", thesame_date) is called twice?
Show answer
The set still contains one date, so the duplicate check-in has no effect.