Sub topic 1
What makes a habit trackable
Prerequisites
This chapter assumes you know the following:
- Basic Python: functions, dictionaries, sets and loops.
- The
dateandtimedeltatypes from thedatetimemodule. - How to read and write a text file.
You do not need to have built anything yet. This is the first chapter, and it sets up the decisions that every later chapter relies on. The code here is small. The main work is deciding what a habit is, so that a program can answer "did I do it today?" with a plain yes or no.
Why the definition comes before the code
A habit tracker is a program that turns a stream of yes/no answers into numbers. The numbers are only as good as the answers. If you can't tell whether you did the habit on a given day, no code will fix that.
Many habits fail at tracking, not because the person lacks discipline, but because the habit was never written in a form that can be checked. "Get healthier" can't be checked on any single day. "Walk for 20 minutes" can.
This chapter covers three things:
- The properties that make a habit trackable.
- How to turn a vague goal into a trackable one.
- How those properties map onto the data model you build in the next chapter.
The four properties of a trackable habit
A habit is trackable when it has these four properties.
| Property | Question it answers | Weak example | Strong example |
|---|---|---|---|
| Binary | Can I answer yes or no? | "Be more active" | "Walk for 20 minutes" |
| Bounded in time | Which calendar day does it belong to? | "Read before the weekend ends" | "Read 10 pages today" |
| Observable | Could I prove it happened? | "Think positively" | "Write one line in my journal" |
| Small enough | Can I do it on a bad day? | "Run 10 km" | "Put on running shoes and go outside" |
Binary
The tracker stores one fact per habit per day: done or not done. It has no field for "partly done". A binary habit means the check-in is a single event. You either log it or you don't.
This is a design choice, and it has a cost. A binary check-in throws away information. Running 2 km and running 15 km both count as "ran". If the amount matters to you, you have two options:
- Pick a threshold that defines success, such as "run at least 2 km". Anything below it is a miss.
- Track the quantity as a second, separate piece of data. That is outside the scope of this tutorial.
The threshold approach keeps the model simple. It is the one the rest of this tutorial uses.
Bounded in time
Every check-in must belong to exactly one calendar day. That is what lets you count streaks and windows later.
Two kinds of wording break this property:
- Open-ended deadlines, such as "sometime this week". You can't say which day to credit.
- Activities that cross midnight, such as "sleep eight hours". Does the night starting on Monday count for Monday or Tuesday?
For the second case, you have to pick a rule and keep to it. For example, "the sleep habit is credited to the day I wake up". The tracker doesn't make this choice for you. It records whatever date you give it.
Observable
You should be able to tell, after the fact, whether the habit happened. This doesn't mean you need proof for other people. It means the answer shouldn't depend on your mood.
"Meditate" is borderline, because on some days you may wonder whether you really meditated or only sat still. "Meditate with a timer for 5 minutes" removes the doubt. The timer finishing is the evidence.
Observability matters because a tracker invites self-deception. If the rule is fuzzy, you will round up on days you feel bad about missing. Your numbers then look better than your behavior, and the review step in the last chapters becomes useless.
Small enough
A habit is easier to sustain when the minimum version is small. If the smallest acceptable action is hard, you will miss days. Each miss breaks the streak and lowers the completion rate. Those numbers then discourage you, which makes the next miss more likely.
A practical test: imagine your worst day this month, with poor sleep, a late meeting and no free time. Could you still do the minimum version? If not, shrink it.
Rewriting a vague goal
You can apply the four properties as a checklist. Start with a goal, find the property it breaks, and rewrite it.
| Vague goal | Property broken | Trackable rewrite |
|---|---|---|
| Eat better | Binary, observable | Eat one piece of fruit with lunch |
| Learn Spanish | Binary, small enough | Complete one lesson in the app |
| Exercise more | Binary, observable | Do 15 minutes of exercise |
| Go to bed earlier | Observable, bounded | Be in bed with the lights off by 23:00 |
| Stop checking my phone | Binary | Leave the phone outside the bedroom overnight |
Notice that each rewrite names a concrete action and, where relevant, a threshold or a time. Several of them also change a negative goal ("stop doing X") into a positive one. A tracker records things that happened. It can't easily record the absence of something, because on a day when you do nothing, you would be logging "nothing" as a success.
Connecting the definition to the data model
Each property has a direct consequence for how the code is shaped.
- Binary means a check-in carries no value besides its date. You don't store a number or a note.
- Bounded in time means the unit of storage is a calendar date, not a timestamp. Two check-ins on the same date are the same check-in.
- Observable means the person, not the program, decides when to log. The program trusts the entry.
- Small enough means a missed day should be rare. The program should still handle misses gracefully, which is the topic of later chapters.
The diagram shows how a written habit definition flows into the pieces you will build.
Everything downstream of the set of dates is arithmetic on dates. That is why the definition has to be right before you write the first function.
A first look at the code
You will build the data model properly in the next chapter. A small preview shows why the binary, one-day-per-check-in design is convenient.
The log is a dictionary that maps each habit name to a set of dates. A set holds each value at most once, so a duplicate check-in on the same day has no effect.
from datetime import date
log = {} # habit name -> set of dates on which it was done
def check_in(habit, day=None):
day = day or date.today()
log.setdefault(habit, set()).add(day)
check_in("read")
check_in("read") # a duplicate check-in on the same day changes nothing
print(len(log["read"])) # 1Reading the code against the four properties:
- The habit is a name only. There is no amount, which matches the binary property.
- The stored value is a
date, not adatetime. This matches the bounded-in-time property, because the time of day is discarded. - The
dayargument defaults to today but can be set. This lets a person log a check-in they forgot, which matters when the observation happens later. setdefaultcreates the empty set the first time a habit is seen, so you never need to register a habit in advance.
Common mistakes
These are the errors people make most often when defining a habit for tracking.
- Defining the habit by outcome. "Lose 2 kg" is a result, not a daily action. You can't check it in on any given day, and it depends on factors you don't control. Track the action that leads to the result.
- Bundling several actions. "Morning routine" hides five actions behind one check-in. If you do four of them, do you log it? Split it into separate habits, or pick the single action that matters most.
- Setting the bar for a good day. A habit that you can meet only when everything goes well will show many misses, and the data then describes your schedule more than your habits.
- Changing the rule mid-way. If you raise the threshold from 5 to 20 minutes, the earlier check-ins no longer mean the same thing. Streaks and rates span both periods and become hard to compare. If you must change the rule, consider starting a new habit name.
- Logging in bulk later. Entering a week of check-ins from memory breaks the observable property. Log close to the time of the action.
Edge cases in the definition
Even a well-written habit meets awkward situations. Decide on these rules now, because the code will later need to match them.
- Travel and time zones. A "day" is a calendar date in your local time. If you fly across zones, the same physical day can appear as two dates. Decide that you always use the local date where you are, and keep to it.
- Illness and planned breaks. The tracker can't tell the difference between a day you chose to skip and a day you forgot. It records a miss either way. If this matters to you, you can decide to treat planned breaks as a separate review note, not as a check-in.
- Habits you don't do every day. If your habit is "go to the gym three times a week", a daily yes/no is the wrong shape. The final chapter in this tutorial returns to non-daily schedules. Until then, track only habits that you intend to do every day.
- Multiple times per day. "Drink water eight times" is a count, not a yes/no. Convert it into a single daily threshold, such as "reach eight glasses", and log once when you reach it.
Checking your definition
Before moving on, pick one habit you want to track and answer these questions. Write the answers down.
- What is the exact action, in one short sentence?
- What is the minimum version that counts?
- Which calendar day does it belong to, and what is the rule if it crosses midnight?
- What will you point to as evidence that it happened?
- Could you do it on your worst day this month?
If you can answer all five without hedging, the habit is trackable. If you hesitate on any, rewrite the habit until you don't. You will use this habit as the running example in the following chapters.
Exercise
A learner writes the goal "Save more money". Rewrite it as a trackable daily habit, and name which of the four properties the original goal breaks.
Show answer
The original breaks the binary property (there is no yes/no answer on a given day), and it is also not observable or small enough. One trackable rewrite is "Transfer 1 euro to my savings account today". It is a single action, it belongs to one calendar day, it can be confirmed in the bank app, and it is small enough to do on a bad day.
Exercise
Why does the tracker store a date and not a datetime for each check-in, and what happens in the code if you check in twice on the same day?
Show answer
Storing a date ties each check-in to a calendar day, which is the bounded-in-time property. The time of day is not needed for a daily yes/no. Because each habit's check-ins are kept in a set, adding the same date a second time has no effect, so len(log["read"]) stays 1.
Exercise
"Don't eat sugar" is a common habit goal. Explain why it is hard to track with a check-in, and give a trackable alternative.
Show answer
A check-in records that something happened. "Don't" habits succeed when nothing happens, so a day with no log entry can mean either success or a forgotten entry. Rephrase it as an action, for example "Eat fruit instead of dessert after dinner", which can be logged when it is done.