A todo list combines data storage with commands. You will build a small task manager that runs in the text console and keeps its state for the duration of the program.
What you will build#
A menu with numbered actions:
- Add a task.
- List tasks.
- Complete a task.
- Delete a task.
- Quit.
Each task stores a title and a completed flag. Task numbers shown to the user start at 1, while Python list indexes start at 0. Converting between the two is a core part of the exercise.
Data model#
Use a list of dictionaries:
tasks = [
{"title": "Read chapter 1", "done": False},
{"title": "Practice loops", "done": True},
]A dictionary keeps the fields named, which is clearer than a list of positional values. Each task is identified by its index in the list for this version.
Requirements#
- Print the menu after every command.
- Reject a menu choice that is not a number from 1 to 5.
- Reject a blank task title.
- Refuse to complete or delete a task number that does not exist.
- Mark completed tasks with
[x]and pending tasks with[ ]. - Print a count such as
2 of 3 tasks complete. - Quit cleanly with a farewell message.
Skeleton#
tasks = []
def show_menu():
print()
print("1. Add task")
print("2. List tasks")
print("3. Complete task")
print("4. Delete task")
print("5. Quit")
def list_tasks():
if not tasks:
print("No tasks yet.")
return
for index, task in enumerate(tasks, start=1):
mark = "x" if task["done"] else " "
print(f"{index}. [{mark}] {task['title']}")
completed = sum(1 for task in tasks if task["done"])
print(f"{completed} of {len(tasks)} tasks complete")
def read_task_number(prompt):
text = input(prompt)
try:
number = int(text)
except ValueError:
print("Enter a task number.")
return None
if number < 1 or number > len(tasks):
print("That task does not exist.")
return None
return number - 1
while True:
show_menu()
command = input("Choose an action: ").strip()
if command == "1":
title = input("Task title: ").strip()
if title:
tasks.append({"title": title, "done": False})
print("Task added.")
else:
print("A task needs a title.")
elif command == "2":
list_tasks()
elif command == "3":
index = read_task_number("Task number to complete: ")
if index is not None:
tasks[index]["done"] = True
print("Task completed.")
elif command == "4":
index = read_task_number("Task number to delete: ")
if index is not None:
removed = tasks.pop(index)
print(f"Deleted: {removed['title']}")
elif command == "5":
print("Goodbye.")
break
else:
print("Choose 1 through 5.")Running it in ILoveCompiler#
The compiler is not a live terminal, so prepare every input line before pressing Run. For a test session, use this input:
1 Buy milk 1 Practice Python 2 3 1 2 4 2 5
The prompts accept the values one after another. Trace the output and confirm that task 1 is completed before it is deleted.
Improve the design#
The single while loop works, but it grows quickly. Refactor each command into a function and use a dictionary dispatch:
actions = {
"1": add_task,
"2": list_tasks,
"3": complete_task,
"4": delete_task,
}
action = actions.get(command)
if action is None:
print("Choose 1 through 5.")
else:
action()This keeps the loop small and makes adding commands easier.
Stretch goals#
- Add priorities (
high,normal,low) and sort the listing by priority. - Store the creation date as a string and show it in the listing.
- Add a
searchcommand that lists matching titles. - Prevent duplicate titles if you decide duplicates are not allowed.
- Persist tasks as JSON text and display the JSON so it could be saved elsewhere.
Testing checklist#
- Add two tasks and list them.
- Complete the first task and verify its marker changes.
- Delete a task and verify the remaining numbers shift correctly.
- Enter
abcfor the menu choice and for a task number. - Enter an out-of-range task number.
- Quit and confirm the loop ends.
