Todo List Manager
What you'll build
A Python TodoList class that adds, completes, removes, and lists tasks, with JSON save/load — a mini task manager.
Goals
- Define a class with __init__ and instance methods
- Use a list of dictionaries to store tasks
- Serialize and deserialize with the json module
- Filter tasks by status with list comprehensions
Prerequisites
- Classes and objects
- Lists and dictionaries
- JSON handling
Steps
- 1
Define the TodoList class
Create a TodoList class with an __init__ that initializes an empty list of tasks. Each task is a dict with 'title' and 'done' keys.
Codeclass TodoList: def __init__(self): self.tasks = [] def add(self, title): self.tasks.append({"title": title, "done": False}) print(f"Added: {title}")Expected result
todo = TodoList(); todo.add('Buy milk') adds a task and prints a confirmation.
- 2
Add complete and remove methods
Add complete(index) that marks a task done, and remove(index) that deletes a task. Include bounds checking.
Codedef complete(self, index): if 0 <= index < len(self.tasks): self.tasks[index]["done"] = True print(f"Completed: {self.tasks[index]['title']}") def remove(self, index): if 0 <= index < len(self.tasks): removed = self.tasks.pop(index) print(f"Removed: {removed['title']}")Expected result
todo.complete(0) marks the first task done; todo.remove(0) deletes it.
- 3
Add display and JSON save/load
Add display() that prints all tasks with status, and save(filename)/load(filename) that serialize to/from JSON.
Codedef display(self): if not self.tasks: print("No tasks.") return for i, task in enumerate(self.tasks): status = "[x]" if task["done"] else "[ ]" print(f"{i}. {status} {task['title']}") def save(self, filename): import json with open(filename, 'w') as f: json.dump(self.tasks, f) def load(self, filename): import json with open(filename, 'r') as f: self.tasks = json.load(f)Expected result
display() shows numbered tasks with [x] or [ ] status. save/load persist to JSON.
- 4
Add input validation & exception handling
Add a try/except block in the main function to handle user input errors, using ValueError to catch illegal conversions. Python's exception handling lets the program degrade gracefully on bad input instead of crashing.
Codedef safe_input(prompt, validator=None): """Read input with validation and error handling.""" while True: try: raw = input(prompt) value = float(raw) if validator and not validator(value): raise ValueError(f"Value {value} failed validation") return value except ValueError as err: print(f"Invalid input: {err}. Please try again.") # Usage age = safe_input("Enter your age: ", lambda x: x > 0)Expected result
Invalid input (non-number or failed validation) prompts for re-entry; valid input returns the number.
- 5
Write unit tests
Write tests for the core function using unittest or assert statements, covering normal paths, boundary values, and exceptions. Tests are the safety net for code quality.
Codeimport unittest class TestCoreFunc(unittest.TestCase): def test_normal(self): self.assertEqual(core_func(5), expected_5) def test_boundary(self): self.assertEqual(core_func(0), expected_0) def test_exception(self): with self.assertRaises(ValueError): core_func(-1) if __name__ == "__main__": unittest.main()Expected result
Running python test.py prints OK with all three test cases passing.
Try it yourself
# TODO: define the TodoList class with add, complete, remove, display, save, load
# Then test:
# todo = TodoList()
# todo.add('Learn Python')
# todo.add('Build project')
# todo.complete(0)
# todo.display()
import json
class TodoList:
def __init__(self):
self.tasks = []
def add(self, title):
self.tasks.append({"title": title, "done": False})
print(f"Added: {title}")
def complete(self, index):
if 0 <= index < len(self.tasks):
self.tasks[index]["done"] = True
print(f"Completed: {self.tasks[index]['title']}")
def remove(self, index):
if 0 <= index < len(self.tasks):
removed = self.tasks.pop(index)
print(f"Removed: {removed['title']}")
def display(self):
if not self.tasks:
print("No tasks.")
return
for i, task in enumerate(self.tasks):
status = "[x]" if task["done"] else "[ ]"
print(f"{i}. {status} {task['title']}")
def save(self, filename):
with open(filename, 'w') as f:
json.dump(self.tasks, f)
def load(self, filename):
with open(filename, 'r') as f:
self.tasks = json.load(f)
todo = TodoList()
todo.add('Learn Python')
todo.add('Build project')
todo.complete(0)
todo.display()What you learned
You built an OOP task manager with state, methods, bounds checking, and JSON persistence — the architecture behind many real-world CLI tools and applications.
Related Resources
Related Lessons
- Classes and Objects
OOP fundamentals.
- JSON Handling
Serialization.
Related Practice
- self Parameter Quiz
Practice OOP.
- Predict Class Output
Predict class behavior.
Related Cheatsheets
- Python Cheatsheet
Class and JSON reference.
Related Errors
- Index Error
Invalid task index.
- Type Error
Type mismatches.
Related Glossary
- Dictionary
Task storage.
- List
Task list.
Related Glossary
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
- Dictionary
Task storage.
- List
Task list.
Related Errors
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
- Index Error
Invalid task index.
- Type Error
Type mismatches.