Codiqo

Learn Python · lesson 46 of 60 · about 10 minutes

Capstone: Core Logic and Interaction

Tick Sam's habits off: write the streak calculation and a command loop that drives the tracker.

What you'll learn

  • Calculate a streak with datetime
  • Process typed commands
  • Connect functions into a working program

Ticking habits off

Sam ticks habits off with commands like done read 2026-11-30, until quit. The command is split once at the first space, and the rest once at its last space, so done drink water 2026-11-30 still finds the habit drink water. Each tick goes into that habit's set, and the assistant says how many days in a row it's been done, counting back from the latest day ticked. Commands that don't fit, habits Sam never added and dates that aren't dates each get a friendly line, and at the end the assistant says how many ticks there are so far.

Counting a streak

A streak is how many days in a row a habit was done, counting back from today. Start at today and step back one day at a time with timedelta(days=1) until you hit a day that's missing.

streak()

from datetime import date, timedelta

def streak(done, today):
    count = 0
    day = today
    while day.isoformat() in done:
        count += 1
        day -= timedelta(days=1)
    return count

done = {"2026-05-01", "2026-05-02", "2026-05-03"}
print(streak(done, date(2026, 5, 3)))
print(streak(done, date(2026, 5, 5)))

Output

3
0

The command loop

The program reads commands like add read or done read, splits off the first word, and calls the right function.

Driving it with commands

habits = {}

while True:
    cmd = input("> ").strip()
    if cmd == "quit":
        break
    action, _, name = cmd.partition(" ")
    if action == "add":
        habits[name] = set()
        print("Added", name)
    elif action == "done" and name in habits:
        habits[name].add("2026-05-03")
        print("Nice work on", name)
    else:
        print("Unknown command")

print(sorted(habits))

Output

> Added read
> Nice work on read
> Unknown command
> ['read']

Tip

partition splits at the first space only, so a habit name with spaces in it, like "drink water", still works.

From the end, too

rpartition(" ") is partition from the right: it splits at the last space. After partition has taken the command word off the front, rpartition takes the date off the end, and whatever is in between is the habit's name, spaces and all.

Splitting from both ends

action, _, rest = "done drink water 2026-11-30".partition(" ")
habit_name, _, day = rest.rpartition(" ")
print(action, "|", habit_name, "|", day)

Output

done | drink water | 2026-11-30

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.