Skip to contentSkip to navigation

Module 06 · Lesson 03

Project: To-Do Task Manager

Build a to-do list manager from lists, dictionaries and functions: add tasks, mark them done, remove them, show them numbered and count what is left.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Tasks as dictionaries
  • One function per action
  • Number tasks from 1
  • Count what is left

The manager in four parts

A to-do list is a list of tasks. Each task is a small dictionary, and each action is a function.

  • The data

    tasks = [{"title": "Read", "done": False}]: one dictionary per task.

  • One function per job

    add_task(), mark_done(), remove_task() and show_tasks().

  • Shown from 1

    People see tasks numbered from 1, so task number 2 is index 1.

  • Count what is left

    A loop counts the tasks whose done is still False.

Lists of tasks everywhere

The same data, a list of small records, sits behind many apps.

  • To-do appsEach task has a title, a tick and sometimes a due date.
  • Shopping listsTick items off as they go in the trolley.
  • Quest logsGames track quests as done or not done, with a count of what is left.
  • Homework plannersSubjects, tasks and ticks, shown as a numbered list.

Ticking a task off

This line marks one task as done. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

the list:The list of every task.

Build the manager in five steps

Build the project one step at a time. Each example runs on its own: change it, then press Run.

Example 1 of 61. The data

A list of dictionaries: every task has the same two keys.

Your turn: Add a third task, then print the title of the last one with [-1].

Python
tasks = [
    {"title": "Feed the cat", "done": False},
    {"title": "Homework", "done": True},
]
print(tasks[0]["title"])
print(len(tasks), "tasks")
Output
Press Run to see what it prints.

Watch tasks get added and ticked

Press Step to run one line at a time. Watch the list in the names box change.

Ready. Press Step to run the first line.

  1. tasks = []
  2. tasks.append({"title": "Homework", "done": False})
  3. tasks.append({"title": "Walk dog", "done": False})
  4. tasks[0]["done"] = True
  5. left = 0
  6. for task in tasks:
  7. if not task["done"]:
  8. left += 1
  9. print(left, "task left")

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Shown number 2: what prints?

tasks = ["Read", "Run", "Swim"]
number = 2
print(tasks[number - 1])

0 of 6 answered

Common task manager misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Building the manager

The brief

The program keeps a list of tasks. The user can add a task, mark one as done by its number, remove one, and see the whole list with checkboxes and a count of what is left. Numbers shown to the user start at 1. Typing a number that does not exist prints a friendly message instead of crashing.

Choosing the data

Each task has two facts: a title and whether it is done. A small dictionary holds them with clear names, and a list keeps the tasks in order.

Try it 1: edit me, then Run
tasks = [
    {"title": "Buy milk", "done": False},
    {"title": "Call Sam", "done": True},
]
Output
Press Run to see what it prints.

Why not two separate lists, one of titles and one of done flags? Because they would have to be kept in step forever. Removing a title but forgetting its flag would silently attach every later flag to the wrong task. Keeping each task's facts together in one dictionary makes that bug impossible.

One function per action

Each thing the user can do becomes one function that takes the task list and changes or reads it. Lists are mutable, so a function that appends to the list it was given changes the caller's list; nothing needs to be returned for that.

Try it 2: edit me, then Run
def add_task(tasks, title):
    tasks.append({"title": title, "done": False})

def show(tasks):
    for number, task in enumerate(tasks, start=1):
        mark = "x" if task["done"] else " "
        print(f"{number}. [{mark}] {task['title']}")
Output
Press Run to see what it prints.

enumerate(tasks, start=1) gives people-friendly numbers while the list itself still counts from 0. Every function that receives a number from the user must convert it back: task number 1 is tasks[0].

Checking the number

A user might type 0, a number past the end, or a word. One helper turns the typed text into a valid index, or None if it is not valid, so the other functions do not repeat the checks.

Try it 3: edit me, then Run
def to_index(tasks, text):
    text = text.strip()
    if not text.isdigit():
        return None
    index = int(text) - 1
    if 0 <= index < len(tasks):
        return index
    return None
Output
Press Run to see what it prints.

Returning None for "no valid answer" is a common Python pattern. Callers check it with is None and print a message.

Try it 4: edit me, then Run
def complete(tasks, text):
    index = to_index(tasks, text)
    if index is None:
        print("No task with that number")
        return
    tasks[index]["done"] = True

def remove(tasks, text):
    index = to_index(tasks, text)
    if index is None:
        print("No task with that number")
        return
    removed = tasks.pop(index)
    print(f"Removed {removed['title']}")
Output
Press Run to see what it prints.

pop(index) removes the task and returns it, so the message can name what was removed. After a removal, every later task moves up one place, which is why numbers are always worked out fresh from the current list.

Counting what is left

A loop with a counter answers "how many are not done?". It is the same counter pattern from the loops lessons, applied to one field of each dictionary.

Try it 5: edit me, then Run
def remaining(tasks):
    count = 0
    for task in tasks:
        if not task["done"]:
            count += 1
    return count
Output
Press Run to see what it prints.

Testing as you build

Write one function, then test it straight away with a few calls before writing the next. Call add_task twice and print the list. Call complete with a good number, with 0, with a number past the end and with a word, and check each result. Remove the first task, the last task and the only task. These small checks take seconds, and they find mistakes while the code is still fresh in your mind, instead of in the middle of a long session with the finished program. The Lab tasks below follow exactly this order: each one builds and checks one piece.

Keeping titles tidy

Users type titles with stray spaces and in any case. Stripping each title when it is added means the list never holds " Buy milk ". If you later add a search or a duplicate check, compare lowercase copies, title.lower(), so Buy Milk and buy milk count as the same task, while still showing the title the way the user typed it.

The main loop

The interactive part is a while True loop that shows a short menu, reads a choice and calls the matching function. Typing q breaks out of the loop.

Try it 6: edit me, then Run
tasks = []
while True:
    choice = input("(a)dd, (d)one, (r)emove, (s)how, (q)uit: ").strip().lower()
    if choice == "q":
        break
    elif choice == "a":
        add_task(tasks, input("Title: ").strip())
    elif choice == "d":
        complete(tasks, input("Number: "))
    elif choice == "r":
        remove(tasks, input("Number: "))
    elif choice == "s":
        show(tasks)
        print(remaining(tasks), "left")
Output
Press Run to see what it prints.

The loop contains no list logic at all; it only routes choices to functions. That separation is what lets the Lab tasks test each function on its own without anyone typing.

Where to go next

Natural extensions are a priority for each task, sorting by priority, editing a title, and refusing empty or duplicate titles. The tasks also disappear when the program ends; saving them to a file is covered in Practical Python, where the same task dictionaries fit straight into the JSON format. That course also shows how to turn the task dictionary and its functions into a class.

Syntax

The general shape of the statements in this lesson.

syntax.py
task = {"title": "Read", "done": False}
tasks.append(task)                    # add
tasks[index]["done"] = True           # complete
removed = tasks.pop(index)            # remove and keep it
for n, task in enumerate(tasks, start=1):   # people count from 1
index = int(text) - 1                 # back to a list index
if 0 <= index < len(tasks): ...       # check before using it
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A session without typing

Beginner

Run a whole session of the manager by calling the functions directly: add three tasks, complete one, try a bad number, remove one and show the result.

Python
def add_task(tasks, title):
    tasks.append({"title": title, "done": False})

def to_index(tasks, text):
    text = text.strip()
    if not text.isdigit():
        return None
    index = int(text) - 1
    return index if 0 <= index < len(tasks) else None

def complete(tasks, text):
    index = to_index(tasks, text)
    if index is None:
        print("No task with that number")
    else:
        tasks[index]["done"] = True

def show(tasks):
    for number, task in enumerate(tasks, start=1):
        mark = "x" if task["done"] else " "
        print(f"{number}. [{mark}] {task['title']}")

tasks = []
for title in ["Buy milk", "Call Sam", "Water plants"]:
    add_task(tasks, title)
complete(tasks, "2")
complete(tasks, "7")
tasks.pop(0)
show(tasks)
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Calling the functions with fixed values replaces the typing, so the result is the same every run. Task 7 does not exist, so the helper returns None and a message is printed instead of an IndexError. After removing the first task, Call Sam becomes number 1, because numbers are always worked out from the current list.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Using the shown number as the index

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
tasks = [{"title": "A", "done": False}, {"title": "B", "done": False}]
number = 2
tasks[number]["done"] = True
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

IndexError: list index out of range

Write this instead

tasks = [{"title": "A", "done": False}, {"title": "B", "done": False}]
number = 2
tasks[number - 1]["done"] = True

Why it happens

People count from 1 but list indexes start at 0, so task number 2 is tasks[1].

In the real world

Where this shows up in software people use every day.

  1. A chores rota for a shared flat

    Home

    Flatmates keep their weekly chores in one list. Each chore records who does it and whether it is done, and the rota shows who still has work left.

    Why Python fits

    The same task dictionary gains one more field, and the counting pattern from the dictionaries lesson turns the list into a per-person summary.

    Python
    chores = [
        {"title": "Bins", "who": "Ana", "done": True},
        {"title": "Hoover", "who": "Bo", "done": False},
        {"title": "Bathroom", "who": "Ana", "done": False},
    ]
    left = {}
    for chore in chores:
        if not chore["done"]:
            left[chore["who"]] = left.get(chore["who"], 0) + 1
    for person in sorted(left):
        print(f"{person}: {left[person]} left")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Why do the Labs call functions instead of using input()?

Automatic checks cannot type. Calling the functions with fixed values tests the same logic and gives the same output every run.

How do I keep the tasks after the program closes?

Save them to a file. Practical Python covers files and the JSON format, which stores lists of dictionaries directly.

Should the task be a class instead?

Later, yes. Classes, covered in Practical Python, bundle the data and its functions together. A dictionary is the right first step.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.