🚀 Mini Projects, lesson 3 of 6
Project: to-do list manager
Store tasks as a list of dicts and drive them with typed commands.
12 min
3 exercises
1 quiz
0/4 solved
Getting Python ready… examples can run in a moment.
A to-do app is a classic first "real" program. Each task is a dictionary, and all tasks live in a list:
{"id": 1, "title": "Buy milk", "done": False}
- Add tasks with unique ids
- Complete, format and count tasks
- Commands: a loop that reads
add,done,listandquit
A list of dicts
Comprehensions and generator expressions make filtering and counting one-liners. Add a fourth task.
Step 1: add tasks
Write add_task(tasks, title):
- strip spaces from the title; raise
ValueErrorif it's empty - the new id is the biggest existing id + 1 (or 1 for an empty list)
- append
{"id": ..., "title": ..., "done": False}and return that dict
Step 2: complete, format, count
Add three functions:
complete_task(tasks, task_id)marks that task done and returnsTrue, or returnsFalseif there's no such idformat_task(task)returns"[x] 1. Buy milk"for a done task and"[ ] 2. Call mum"otherwisepending_count(tasks)returns how many aren't done
Step 3: commands. The program reads commands like
add Buy milk or done 2. Split each one into the
action and the rest with
command.partition(" "), then hand it to
handle(tasks, command), which returns the text to
show. Keeping handle free of input() makes it easy
to test.
What does this print?
Parsing commands
rest is '' when there's nothing after the action.
isdigit() lets you check for a number before calling
int().
Step 3: the command loop
Finish handle(tasks, command) so it returns:
add <title>→"Added #<id>: <title>", or"Title can't be empty"on a ValueErrordone <id>→"Completed #<id>", or"No task #<id>"if it doesn't existlist→ everyformat_taskline, then"<n> left to do", joined with newlines ("Nothing to do!"when there are no tasks)- anything else →
"Unknown command: <action>"
The loop at the bottom is done: it reads commands
until quit.
Your program receives this input: add Buy milk ⏎ add Call mum ⏎ done 1 ⏎ list ⏎ quit