Codiqo

Learn Python · lesson 48 of 60 · about 9 minutes

Capstone: Polishing

Finish Sam's tracker with a tidy report, and see what makes code clean and readable.

What you'll learn

  • Format output neatly
  • Organise code with a main function
  • Review what makes code readable

The habit report

The last touch is a report Sam will want to read: a heading, then one line per habit with the name in 12 characters on the left and the streak in 6 on the right, so the numbers line up. The longest streak comes first, and habits with the same streak go in name order. A habit done 3 days or more in a row gets a flame. With no habits, the assistant just says there's nothing to report.

Small touches, big difference

Polish is what turns a working program into one people enjoy using:

  • Line output up in columns with f-string widths like {name:<8}
  • Add a help command that lists what's possible
  • Put the program's start-up code in a main() function

A neat report

streaks = {"read": 12, "walk": 3, "meditate": 0}

print(f"{'Habit':<10}{'Streak':>6}")
for name, days in sorted(streaks.items(), key=lambda kv: -kv[1]):
    flame = "🔥" if days >= 3 else ""
    print(f"{name:<10}{days:>6} {flame}".rstrip())

Output

Habit     Streak
read          12 🔥
walk           3 🔥
meditate       0

main() and the entry point

if __name__ == "__main__": means "only run this when the file is started directly", not when another file imports it. It's how real Python programs begin.

The finished shape

HELP = "Commands: add <habit>, done <habit>, list, help, quit"

def main():
    print("Habit Tracker")
    print(HELP)

if __name__ == "__main__":
    main()

Output

Habit Tracker
Commands: add <habit>, done <habit>, list, help, quit

Tip

You've built a real program from scratch: data model, logic, input, files, error handling and tests. Try adding a feature of your own, like a best-ever streak.

Now try it yourself

This lesson is free in Codiqo, with 10 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.