Sub topic 3
A Minimal Command-Line Interface
Assume you know Python functions, dictionaries, sets, loops, datetime.date, timedelta, and text files. A command-line interface (CLI) lets a user run a program by typing commands in a terminal.
A small tracker needs two commands:
check HABITrecords today.show HABITdisplays useful metrics.
import argparse
from datetime import date
logs = {"read": {date(2026, 11, 25), date(2026, 11, 26)}}
def check_in(habit, day=None):
logs.setdefault(habit, set()).add(day or date.today())
def current_streak(days, today=None):
today = today or date.today()
day = today if today in days else today.fromordinal(today.toordinal() - 1)
streak = 0
while day in days:
streak += 1
day = day.fromordinal(day.toordinal() - 1)
return streak
parser = argparse.ArgumentParser(prog="habit")
sub = parser.add_subparsers(dest="command", required=True)
check = sub.add_parser("check")
check.add_argument("habit")
show = sub.add_parser("show")
show.add_argument("habit")
args = parser.parse_args()
if args.command == "check":
check_in(args.habit)
print(f"Recorded: {args.habit}")
else:
days = logs.get(args.habit, set())
print(f"Current streak: {current_streak(days)}")
print(f"Logged days: {len(days)}")In a finished program, load the logs before parsing commands and save them after check_in. The subcommand determines which action runs.
A set makes duplicate check-ins harmless. Adding the same date twice leaves one date. For a gap, the loop stops at the first absent date. The longest streak and completion rate should also use dates, not the number of commands entered.
Review the numbers over a fixed period. A 30-day completion rate shows consistency better than a long streak alone. If the rate is low, reduce the habit's scope or choose a more suitable trigger. For example, change “exercise for an hour daily” to “walk for ten minutes after lunch.”
Daily streaks are the wrong metric for non-daily habits. For a habit planned three times per week, store the check-in dates but compare them with eligible planned days. Measure completed planned sessions divided by planned sessions, rather than treating every calendar day as a failure.
Exercise
Why does a set fit check-in data better than a list?
Show answer
A set stores each date once, so duplicate check-ins cannot inflate streaks or completion counts.