Chuyển đến nội dung

Bài 142 · Projects

Final project: Build a Command-Line Study Tracker

Build a small command-line study tracker step by step in Python, with input checks, totals, JSON saving, simple tests and a Git history of your work.

Noor is a made-up student who studies several subjects and keeps losing track of where the time goes. In this project you will build her a small program called study. You type a command in a terminal, and it records a study session or shows a report.

At the end you will have a working program on your own computer, a data file that survives after the program closes, a few tests and a Git history that shows how the program grew. It uses only Python's standard library. The idea is small on purpose, so you can understand every line.

What you need first

This is the last step of the New to Programming path:

The checkpoints run in your browser. The program that saves files, the terminal commands and Git all need to run on your own computer with Python and Git installed.

The brief

Your tracker must do the following:

  1. add SUBJECT MINUTES records one session.
  2. total shows the minutes for each subject, largest first, with ties in alphabetical order.
  3. Subject names ignore capital letters and extra spaces at the ends, so Math and math are the same subject.
  4. Minutes must be a whole number from 1 to 600.
  5. Bad input produces a helpful message, not a long error report, and changes nothing.
  6. Sessions are saved in a JSON file and loaded the next time.
  7. The code is split into small functions, and you commit each working step with Git.

Here is how a session might look:

TEXT
$ python study.py add Math 30
Added 30 minutes of math.
$ python study.py add History 45
Added 45 minutes of history.
$ python study.py total
history: 45
math: 30

Milestones

Milestone 1: Set up the project and Git

Create a folder named study-tracker containing study.py and a short README.md that says what the program will do. Run git init, then check git status before you stage anything.

Add a .gitignore file that lists sessions.json and __pycache__/. The data file belongs to the person using the program, not to the source code. Then make your first commit:

Terminal
git add README.md .gitignore study.py
git commit -m "Start the study tracker"

Before writing more code, decide how to store one session. A dictionary such as {"subject": "math", "minutes": 30} is easy to read, and a list can hold many of them in the order they happened.

Hint: If Git asks who you are, follow the message to set your name and email for your commits.

Done when: git status reports a clean working tree and git log shows one commit.

Milestone 2: Accept only good sessions

Everything typed in a terminal arrives as text. Check it at the edge of your program so the rest of the code can trust its data. Write one function that either returns a clean session or raises ValueError with a message.

Python Create a valid session

Your task: Write make_session(subject, minutes_text). Both arguments are strings. Remove spaces from both ends of each and lowercase the subject. Return {"subject": ..., "minutes": ...} with minutes as an int. Raise ValueError("subject is required") if the subject is empty. Otherwise raise ValueError("minutes must be a whole number from 1 to 600") if the minutes text is not made only of digits or is outside 1 to 600.

Hint

The string method isdecimal() is False for empty text, minus signs and decimal points.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

def make_session(subject, minutes_text):
    name = subject.strip().lower()
    if not name:
        raise ValueError("subject is required")
    text = minutes_text.strip()
    if not text.isdecimal() or not 1 <= int(text) <= 600:
        raise ValueError("minutes must be a whole number from 1 to 600")
    return {"subject": name, "minutes": int(text)}

Copy your working function into study.py and commit it with a message such as Validate new sessions.

Done when: the checkpoint passes and the commit is in your history.

Milestone 3: Add up the time

The total report needs two steps: combine minutes by subject, then sort the result. A dictionary is a good fit for combining because it finds a subject quickly. A dictionary has no "largest first" order of its own, so you create a sorted list at the end.

Python Total the minutes by subject

Your task: Write totals(sessions). Each session is a dict with subject and minutes. Return a list of (subject, total_minutes) tuples, ordered by total from largest to smallest. Break ties by subject from A to Z. Do not change the input.

Hint

Use get(name, 0) while adding, then sorted() with a tuple as the key.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

def totals(sessions):
    by_subject = {}
    for session in sessions:
        name = session["subject"]
        by_subject[name] = by_subject.get(name, 0) + session["minutes"]
    return sorted(by_subject.items(), key=lambda item: (-item[1], item[0]))

Done when: your report puts the largest total first and ties come out alphabetically. Commit it.

Milestone 4: Turn commands into actions

Now connect the pieces. Keep the "thinking" apart from the terminal and the file. A function that receives a list of words and returns a message is much easier to test than one that reads and prints everywhere.

The checkpoint includes small versions of the two earlier functions, so you can concentrate on the new one.

Python Handle a command

Your task: Write run_command(sessions, args), where args is a list of strings. For ["add", subject, minutes], call make_session, append the result to sessions and return Added N minutes of SUBJECT. For ["total"], return one subject: minutes line per tuple from totals, joined with newlines, or No sessions yet. if there are none. If make_session raises ValueError, return Error: followed by its message. For anything else, including a wrong number of words, return Usage: add SUBJECT MINUTES | total.

Hint

Check the length of args before you read args[1].

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

def make_session(subject, minutes_text):
    name = subject.strip().lower()
    text = minutes_text.strip()
    if not name:
        raise ValueError("subject is required")
    if not text.isdecimal() or not 1 <= int(text) <= 600:
        raise ValueError("minutes must be a whole number from 1 to 600")
    return {"subject": name, "minutes": int(text)}

def totals(sessions):
    result = {}
    for s in sessions:
        result[s["subject"]] = result.get(s["subject"], 0) + s["minutes"]
    return sorted(result.items(), key=lambda item: (-item[1], item[0]))

def run_command(sessions, args):
    if len(args) == 3 and args[0] == "add":
        try:
            session = make_session(args[1], args[2])
        except ValueError as error:
            return f"Error: {error}"
        sessions.append(session)
        return f"Added {session['minutes']} minutes of {session['subject']}."
    if args == ["total"]:
        lines = [f"{name}: {minutes}" for name, minutes in totals(sessions)]
        return "\n".join(lines) or "No sessions yet."
    return "Usage: add SUBJECT MINUTES | total"

Done when: valid commands work, invalid ones leave the list unchanged, and you have committed the result.

Milestone 5: Save and load

So far, the sessions disappear when the program ends. Memory is temporary; a file stays on the drive. Add the code below to your own study.py, along with your three functions. It uses a data file next to the program.

Python
import json
import sys
from pathlib import Path

DATA_FILE = Path(__file__).with_name("sessions.json")


def load_sessions(path):
    if not path.exists():
        return []
    return json.loads(path.read_text(encoding="utf-8"))


def save_sessions(path, sessions):
    path.write_text(json.dumps(sessions, indent=2), encoding="utf-8")


def main():
    try:
        sessions = load_sessions(DATA_FILE)
    except json.JSONDecodeError:
        print("Error: sessions.json is damaged. It was not changed.")
        return
    count = len(sessions)
    print(run_command(sessions, sys.argv[1:]))
    if len(sessions) != count:
        save_sessions(DATA_FILE, sessions)


if __name__ == "__main__":
    main()

sys.argv is the list of words from the command line. Its first item is the program name, so you pass only the rest. The program saves only when a session was added. It refuses to overwrite a damaged file, which would destroy Noor's records. This handles broken JSON, not every possible problem, such as valid JSON with the wrong shape. Command-line programs explains more about arguments.

Hint: For a subject with spaces, use quotation marks: python study.py add "world history" 25. On some computers the command is py or python3.

Done when: you add two sessions in separate runs and total shows both. git status must not offer to commit sessions.json.

Milestone 6: Test, add a feature on a branch and explain

Create test_study.py with a few checks using plain assert or the testing tools you learned. Cover the limits 1 and 600, one rejected value, tied totals and an unknown command. Importing study will not run main() because of the final if statement.

Then create a branch and add one feature there, such as goal SUBJECT MINUTES, which reports how many minutes remain without storing anything. Never show a number below zero. Run your tests, commit, merge the branch and run the tests again. Finish the README with setup steps, example commands and known limits.

Done when: someone else can follow your README, run the program and the tests, and understand your commit messages.

Check your work

The checkpoints only compare what your functions return. The site cannot run your files or read your Git history, so check the whole project yourself.

Criterion What good looks like
Behavior Both commands match the brief
Input Bad values give clear messages and save nothing
Saving Data remains after the program closes
Design Small functions each have one job, with clear names
Tests Limits, ties and errors are covered and pass
Git Several small commits with meaningful messages
README A new user can run the project without asking you

Common mistakes

Watch for these: converting text with int() before checking it, saving an empty list over a damaged file, using print() inside a function that should return a value, and waiting until the end to make one giant commit. If something breaks, read the last line of the error message first, then find the line number in your own file.

Take it further

  • Add a date to each session. Pass the date into your function, so tests can supply a fixed one.
  • Add a list command with numbered sessions, then a safe way to delete one.
  • Replace your manual argument checks with argparse and compare the two versions.
  • Export the totals as CSV.
  • Totalling visits every session once. Explain why, then use Big O notation to describe the cost of sorting the subjects.
  • Push the repository to a hosting service if you want a copy online. Check first that it contains no private data.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Why does make_session check the text before the rest of the program uses it?

    Checking at the edge keeps invalid values out of the list and the saved file.
  2. 2. What does sys.argv[1:] contain when you run python study.py add art 10?

    The slice skips the program name at position zero. Every argument is a string.
  3. 3. Why is a dictionary useful while you total the minutes?

    The subject is the key. Sorting is a separate step.
  4. 4. Why is sessions.json listed in .gitignore?

    Ignoring it helps keep personal records out of your commits. A file already tracked is not ignored automatically.
  5. 5. Which design is easiest to test?

    You can call it with sample values and compare the result, without a terminal or a file.

Summary

  • You broke one program into validation, totals, commands and saving.
  • Input from a terminal is text and needs checking.
  • A list stores sessions, a dictionary combines them and sorting prepares the report.
  • JSON lets data last between runs.
  • Tests protect behavior while you add features.
  • Small Git commits and a branch record how your work developed.

You can now explain a whole small program that you built. A good next step is to pick a specialty from the learning paths that interests you.

Back to the path: New to Programming learning path

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.