Skip to content
Python project #05Beginner

To-Do List Manager

Manage tasks with priorities, due dates, overdue warnings, completion tracking and statistics from a simple command line.

Estimated time
~3 hours to build
Files
4 files · 327 lines
Technologies
Python 3, dataclasses, datetime.date

Introduction

A to-do list is the classic CRUD (create, read, update, delete) application. This version adds priorities, due dates relative to a configurable 'today', smart sorting and statistics.

Problem statement

Provide commands to add tasks with optional !high/!low priority and 'due YYYY-MM-DD', list pending tasks sorted by priority then due date, list all or completed tasks, mark tasks done or not done, remove tasks, clear completed ones and show statistics. Show 'OVERDUE', 'due TODAY' or 'due in N days'. Invalid dates, missing titles and unknown task numbers must give clear errors.

Objectives

  • Build a command loop with dispatch on the first word
  • Use datetime.date for due-date arithmetic
  • Sort with a tuple key
  • Keep task numbers stable after deletions

Features

  • High, normal and low priorities
  • Due dates with overdue, today and days-left labels
  • Sorting by priority, then due date, then number
  • done / undo / remove / clear
  • Statistics with completion rate

Concepts demonstrated

  • CRUD operations
  • Date arithmetic
  • Sorting with tuple keys
  • Exceptions for invalid input

System architecture

Task is a dataclass with a describe method that builds the display line relative to today. TodoList.add parses the words of an add command, pulling out priority and due-date options and keeping the rest as the title. pending_sorted sorts by a (priority, due date, number) tuple, using date.max for tasks without a due date. run dispatches a command; main handles errors and the loop.

Folder structure

TextProject tree
todo-list-manager/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

153 lines
Pythonmain.py
"""To-Do List Manager with priorities, due dates, overdue warnings and statistics.
Commands:
today YYYY-MM-DD set today's date (defaults to the real date)
add <title> [!high|!low] [due YYYY-MM-DD]
list [all|done|pending] pending tasks are sorted by priority then due date
done <n> / undo <n> / remove <n>
clear remove completed tasks
stats
quit
"""
import sys
from dataclasses import dataclass
from datetime import date
PRIORITY_ORDER = {"high": 0, "normal": 1, "low": 2}
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip()
@dataclass
class Task:
number: int
title: str
priority: str = "normal"
due: date | None = None
done: bool = False
def describe(self, today: date) -> str:
box = "[x]" if self.done else "[ ]"
flag = {"high": " (!)", "low": " (low)"}.get(self.priority, "")
due = ""
if self.due:
days = (self.due - today).days
if self.done:
due = f" due {self.due:%d %b}"
elif days < 0:
due = f" OVERDUE by {-days} day{'s' if days != -1 else ''}"
elif days == 0:
due = " due TODAY"
else:
due = f" due in {days} day{'s' if days != 1 else ''}"
return f"{self.number:>3}. {box} {self.title}{flag}{due}"
class TodoList:
def __init__(self):
self.tasks: list[Task] = []
self.next_number = 1
self.today = date.today()
def add(self, words: list[str]) -> Task:
priority, due, title_words = "normal", None, []
i = 0
while i < len(words):
word = words[i]
if word.lower() in ("!high", "!low"):
priority = word[1:].lower()
elif word.lower() == "due" and i + 1 < len(words):
try:
due = date.fromisoformat(words[i + 1])
except ValueError:
raise ValueError(f"'{words[i + 1]}' is not a date (use YYYY-MM-DD)") from None
i += 1
else:
title_words.append(word)
i += 1
if not title_words:
raise ValueError("a task needs a title")
task = Task(self.next_number, " ".join(title_words), priority, due)
self.next_number += 1
self.tasks.append(task)
return task
def get(self, text: str) -> Task:
if not text.isdigit():
raise ValueError(f"'{text}' is not a task number")
for task in self.tasks:
if task.number == int(text):
return task
raise ValueError(f"there is no task {text}")
def pending_sorted(self) -> list[Task]:
pending = [t for t in self.tasks if not t.done]
return sorted(pending, key=lambda t: (PRIORITY_ORDER[t.priority], t.due or date.max, t.number))
def run(app: TodoList, line: str) -> None:
command, *args = line.split()
command = command.lower()
if command == "today":
app.today = date.fromisoformat(args[0])
print(f"Today is {app.today:%A %d %B %Y}.")
elif command == "add":
task = app.add(args)
print(f"Added: {task.describe(app.today).strip()}")
elif command == "list":
which = args[0].lower() if args else "pending"
tasks = {"all": app.tasks, "done": [t for t in app.tasks if t.done]}.get(which, app.pending_sorted())
if not tasks:
print("Nothing to show.")
for task in tasks:
print(task.describe(app.today))
elif command in ("done", "undo"):
task = app.get(args[0] if args else "")
task.done = command == "done"
print(f"{'Completed' if task.done else 'Reopened'}: {task.title}")
elif command == "remove":
task = app.get(args[0] if args else "")
app.tasks.remove(task)
print(f"Removed: {task.title}")
elif command == "clear":
before = len(app.tasks)
app.tasks = [t for t in app.tasks if not t.done]
print(f"Cleared {before - len(app.tasks)} completed task(s).")
elif command == "stats":
done = sum(t.done for t in app.tasks)
overdue = sum(1 for t in app.tasks if not t.done and t.due and t.due < app.today)
total = len(app.tasks)
rate = f"{done / total:.0%}" if total else "-"
print(f"{total} tasks: {done} done, {total - done} pending, {overdue} overdue. Completion {rate}.")
else:
raise ValueError("unknown command (today, add, list, done, undo, remove, clear, stats, quit)")
def main() -> None:
app = TodoList()
print("To-Do List Manager")
while True:
line = ask("> ")
if line is None or line.lower() == "quit":
break
if not line:
continue
try:
run(app, line)
except (ValueError, IndexError) as error:
print(f"Error: {error}")
print(f"Bye! {sum(not t.done for t in app.tasks)} task(s) still pending.")
if __name__ == "__main__":
main()

What each file does

main.py
The whole program: data classes, validation, the command loop and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
To-Do List Manager
> today 2026-11-27
Today is Friday 27 November 2026.
> add Submit lab record !high due 2026-11-26
Added: 1. [ ] Submit lab record (!) OVERDUE by 1 day
> add Buy groceries
Added: 2. [ ] Buy groceries
> add Revise Python OOP !high due 2026-11-30
Added: 3. [ ] Revise Python OOP (!) due in 3 days
> add Call the bank due 2026-11-27
Added: 4. [ ] Call the bank due TODAY
> add Clean the room !low
Added: 5. [ ] Clean the room (low)
> add !high
Error: a task needs a title
> add Pay fees due 27-11-2026
Error: '27-11-2026' is not a date (use YYYY-MM-DD)
> list
1. [ ] Submit lab record (!) OVERDUE by 1 day
3. [ ] Revise Python OOP (!) due in 3 days
4. [ ] Call the bank due TODAY
2. [ ] Buy groceries
5. [ ] Clean the room (low)
> done 2
Completed: Buy groceries
> done 4
Completed: Call the bank
> done 9
Error: there is no task 9
> list all
1. [ ] Submit lab record (!) OVERDUE by 1 day
2. [x] Buy groceries
3. [ ] Revise Python OOP (!) due in 3 days
4. [x] Call the bank due 27 Nov
5. [ ] Clean the room (low)
> undo 4
Reopened: Call the bank
> clear
Cleared 1 completed task(s).
> stats
4 tasks: 0 done, 4 pending, 1 overdue. Completion 0%.
> remove 5
Removed: Clean the room
> list
1. [ ] Submit lab record (!) OVERDUE by 1 day
3. [ ] Revise Python OOP (!) due in 3 days
4. [ ] Call the bank due TODAY
> quit
Bye! 3 task(s) still pending.
Input
today 2026-11-27
add Submit lab record !high due 2026-11-26
add Buy groceries
add Revise Python OOP !high due 2026-11-30
add Call the bank due 2026-11-27
add Clean the room !low
add !high
add Pay fees due 27-11-2026
list
done 2
done 4
done 9
list all
undo 4
clear
stats
remove 5
list
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • With today set to 27 November 2026, the lab record is overdue by 1 day and the bank call is due today.
  • A task with no title and a date in the wrong format are rejected.
  • After undo 4 and clear, stats report 4 tasks with 1 overdue.

Common errors

Sorting fails when some tasks have no due date

Use t.due or date.max so missing dates sort last instead of comparing None with a date.

Task numbers change after deleting

Give each task a permanent number from a counter rather than using list positions.

Possible improvements

  • Save tasks to a JSON file between runs
  • Add tags and filter by tag
  • Add recurring tasks such as 'every Monday'

Additional challenges

  1. 1Add an 'edit <n> <new title>' command.
  2. 2Show tasks grouped under Today, This week and Later headings.
  3. 3Add an 'agenda' command that lists the next 7 days.

Built and tested it yourself? Mark it to update your dashboard.