Project: to-do list manager

Mini Projects, lesson 3 of 6

🚀 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}
  1. Add tasks with unique ids
  2. Complete, format and count tasks
  3. Commands: a loop that reads add, done, list and quit
Example

A list of dicts

Comprehensions and generator expressions make filtering and counting one-liners. Add a fourth task.

Exercise

Step 1: add tasks

Write add_task(tasks, title):

  • strip spaces from the title; raise ValueError if 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
Exercise

Step 2: complete, format, count

Add three functions:

  • complete_task(tasks, task_id) marks that task done and returns True, or returns False if there's no such id
  • format_task(task) returns "[x] 1. Buy milk" for a done task and "[ ] 2. Call mum" otherwise
  • pending_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.

Quiz

What does this print?

Example

Parsing commands

rest is '' when there's nothing after the action. isdigit() lets you check for a number before calling int().

Exercise

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 ValueError
  • done <id> → "Completed #<id>", or "No task #<id>" if it doesn't exist
  • list → every format_task line, 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