Lesson 30 of 30
In progress
Capstone: a task manager that remembers
Build a small task manager with JSON storage, command handling and validation, then extend it without rewriting it.
This is the last lesson in the track, and it uses everything: functions, lists of dictionaries, JSON, error handling and a command loop. The goal is not a product. It is a program you can explain line by line.
What you will learn
- Model tasks as a list of dictionaries with ids derived from the data.
- Separate commands, lookup and rendering so each can be tested alone.
- Recover from bad input at the command boundary instead of crashing.
- Persist the list to JSON without risking a half-written file.
What you will build
A task manager with four commands:
add <title>creates a task with a unique id.listshows every task and whether it is done.done <id>marks one task complete.remove <id>deletes a task.
Tasks are a list of dictionaries. JSON stores them. Invalid ids and empty titles are refused with a message rather than a traceback.
Start with the data shape
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def new_task(title, task_id):
return {"id": task_id, "title": title, "done": False}
def next_id(tasks):
return max((task["id"] for task in tasks), default=0) + 1
tasks = []
tasks.append(new_task("Read module 6", next_id(tasks)))
tasks.append(new_task("Build the capstone", next_id(tasks)))
print(json.dumps(tasks, indent=2))
Press Run to see the output.
next_id uses max with a default of zero, so the first task gets id 1 and no counter has to be stored separately. Deriving the id from the data means a hand-edited file cannot leave the counter out of sync.
Commands as functions
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def find(tasks, task_id):
for task in tasks:
if task["id"] == task_id:
return task
raise ValueError(f"No task with id {task_id}")
def complete(tasks, task_id):
task = find(tasks, task_id)
task["done"] = True
return task
def remove(tasks, task_id):
task = find(tasks, task_id)
tasks.remove(task)
return task
def render(tasks):
if not tasks:
return "No tasks yet."
lines = []
for task in tasks:
mark = "x" if task["done"] else " "
lines.append(f"[{mark}] {task['id']}. {task['title']}")
return "n".join(lines)
Press Run to see the output.
find is the only place that knows how lookup works, so complete and remove cannot disagree about what "not found" means. render returns a string instead of printing, which keeps it usable in a test.
A command loop that survives mistakes
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
command = parts[0].lower()
argument = parts[1] if len(parts) > 1 else ""
try:
if command == "add":
task = add(tasks, argument)
return f"Added: {task['title']}"
if command == "list":
return render(tasks)
if command in ("done", "remove"):
task_id = int(argument)
if command == "done":
complete(tasks, task_id)
return f"Completed {task_id}"
remove(tasks, task_id)
return f"Removed {task_id}"
return f"Unknown command: {command}"
except ValueError as error:
return f"Error: {error}"
tasks = []
for line in ["add Read module 6", "add Build capstone", "list", "done 1", "list", "done 9"]:
print(">", line)
print(run(tasks, line))
Press Run to see the output.
int(argument) can raise ValueError for "done nine", and find raises it for a missing id; one handler covers both and prints a sentence instead of a traceback. That is the difference between a script and a tool.
Persistence
The runnable version above keeps tasks in memory because this page cannot rely on writable disk. On your machine, add two functions around the same list.
import json
from pathlib import Path
DATA = Path(__file__).parent / "tasks.json"
def load():
try:
return json.loads(DATA.read_text(encoding="utf-8"))
except FileNotFoundError:
return []
except json.JSONDecodeError:
print("tasks.json is damaged; starting with an empty list")
return []
def save(tasks):
temporary = DATA.with_suffix(".tmp")
temporary.write_text(json.dumps(tasks, indent=2, ensure_ascii=False), encoding="utf-8")
temporary.replace(DATA)
Load once at startup, save after every command that changes the list. Writing to a temporary file and replacing avoids leaving a half-written JSON file if the process stops mid-save. The FileNotFoundError branch makes the first run work; the JSONDecodeError branch keeps a damaged file from ending the program.
Call save(tasks) inside add, complete and remove, or in the loop after a successful command. Saving in one place after success is simpler and avoids writing on failed commands.
Extend it without rewriting it
The structure pays off when requirements change:
- Priorities: add
"priority": "normal"innew_taskand a--priorityargument;rendersorts by it. - Due dates: store ISO strings, compare them as strings, and format for display.
- Search: filter
tasksby a substring, then reuserender. - Multiple lists: turn
tasksinto a dictionary keyed by list name, and pass the chosen list into the same functions.
Each extension touches one function because each function has one job. That is the point of the whole track.
Forgetting to save after a successful change is the classic capstone bug: the command reports success, the list looks right, and the data vanishes on restart. Test it deliberately: add a task, exit, start again, list. If the file is empty, the save call is in the wrong branch or the path points somewhere unexpected.
Add a --all style filter to render: given a show argument of "open", print only unfinished tasks. Then make missing count how many tasks are unfinished and print it after the list.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
lines = []
for task in visible:
mark = "x" if task["done"] else " "
lines.append(f"[{mark}] {task['id']}. {task['title']}")
open_count = len([t for t in tasks if not t["done"]])
lines.append(f"{open_count} open")
return "n".join(lines)
tasks = [
{"id": 1, "title": "Read", "done": True},
{"id": 2, "title": "Build", "done": False}
]
print(render(tasks, "open"))
print(render(tasks))
Press Run to see the output.
Filtering happens before rendering, and the open count is computed from the full list so it stays correct when the filter hides completed tasks.
Where to go next
You have finished the Python track. The next useful steps are testing with unittest or pytest, working with an API using urllib.request, and packaging a script so it can be installed. All three build directly on modules, JSON and error handling.
Recap
- Model tasks as dictionaries, derive ids from the data, and keep lookup in one function.
- Handle
ValueErrorat the command boundary so bad input produces a sentence. - Save through a temporary file, and test persistence by restarting.
Why not use a database?
How would I add tests to this project?
Progress is saved in this browser only. No account, no email.