The Task
Build a to-do list program that:
- Shows a menu with these options: View tasks, Add a task, Update a task, Remove a task, and Quit.
- Stores tasks in a list.
- Shows tasks as a numbered list, starting from
1. - Keeps showing the menu until the user chooses Quit.
- Handles special cases: an empty list, an empty task, and a task number that doesn’t exist.
- Shows a message if the user enters an invalid menu option.
What You’ll Use
- A list to store the tasks.
- Functions that receive the list as a parameter.
append(),pop(), andindexassignment to add, remove, and update tasks.enumerate()withstart=1for the numbered view.while Truewithbreakandmatch-casefor the menu.input(),int(), andstrip()to take and clean input.ifandelseto handle special cases.
Expected Output
Here’s an example of how the program might work. The menu appears again after each action.
--- To-Do List ---
1. View tasks
2. Add a task
3. Update a task
4. Remove a task
5. Quit
Choose an option (1-5): 2
Enter the task: Buy milk
Task added.
--- To-Do List ---
1. View tasks
2. Add a task
3. Update a task
4. Remove a task
5. Quit
Choose an option (1-5): 2
Enter the task: Study Python
Task added.
--- To-Do List ---
1. View tasks
2. Add a task
3. Update a task
4. Remove a task
5. Quit
Choose an option (1-5): 1
1. Buy milk
2. Study Python
--- To-Do List ---
1. View tasks
2. Add a task
3. Update a task
4. Remove a task
5. Quit
Choose an option (1-5): 4
1. Buy milk
2. Study Python
Enter the task number to remove: 1
Removed: Buy milk
--- To-Do List ---
1. View tasks
2. Add a task
3. Update a task
4. Remove a task
5. Quit
Choose an option (1-5): 5
Goodbye!Try It Yourself First
Here are a few hints:
- Create an empty list before the loop starts. Every option should work on this same list.
- Write each action as its own function, and pass the list in as a parameter.
- Users count from
1, but list indexes start at0. Subtract1from the task number to get the correct index. - Check that the number is between
1andlen(tasks)before using it. pop(index)removes an item and returns it, so you can show what was removed.- Use
strip()to remove extra spaces from task input.
Give it a try before you scroll down!
Solution
# To-Do List
def show_tasks(tasks):
if len(tasks) == 0:
print("No tasks yet.")
else:
for number, task in enumerate(tasks, start=1):
print(f"{number}. {task}")
def add_task(tasks, task):
tasks.append(task)
def update_task(tasks, number, new_task):
tasks[number - 1] = new_task
def remove_task(tasks, number):
return tasks.pop(number - 1)
tasks = []
while True:
print("\n--- To-Do List ---")
print("1. View tasks")
print("2. Add a task")
print("3. Update a task")
print("4. Remove a task")
print("5. Quit")
choice = input("Choose an option (1-5): ").strip()
match choice:
case "1":
show_tasks(tasks)
case "2":
task = input("Enter the task: ").strip()
if task == "":
print("A task can't be empty.")
else:
add_task(tasks, task)
print("Task added.")
case "3":
if len(tasks) == 0:
print("No tasks to update.")
else:
show_tasks(tasks)
number = int(
input("Enter the task number to update: ")
)
if 1 <= number <= len(tasks):
new_task = input("Enter the new task: ").strip()
if new_task == "":
print("A task can't be empty.")
else:
update_task(tasks, number, new_task)
print("Task updated.")
else:
print("Invalid task number.")
case "4":
if len(tasks) == 0:
print("No tasks to remove.")
else:
show_tasks(tasks)
number = int(
input("Enter the task number to remove: ")
)
if 1 <= number <= len(tasks):
removed = remove_task(tasks, number)
print(f"Removed: {removed}")
else:
print("Invalid task number.")
case "5":
print("Goodbye!")
break
case _:
print("Invalid option. Please choose a number from 1 to 5.")How It Works
1. Creating the list
tasks = []We create an empty list before the loop starts. This is important because every menu option needs to work with the same list.
If we created the list inside the loop, it would be reset each time the menu appeared.
2. Using functions
Each action has its own function:
show_tasks(tasks)displays the tasks.add_task(tasks, task)adds a new task.update_task(tasks, number, new_task)changes an existing task.remove_task(tasks, number)removes a task and returns it.
Passing the list to these functions lets us work with the same list throughout the program.
3. Showing numbered tasks
We use enumerate(tasks, start=1) to display the tasks with numbers starting from 1.
for number, task in enumerate(tasks, start=1):
print(f"{number}. {task}")This makes the list easier for users to read. Remember, the actual list indexes still start at 0.
4. Converting task numbers to indexes
Suppose a user wants to remove task number 2.
The second task is stored at index 1, so we use number - 1 when accessing the list.
Before updating or removing a task, we check:
if 1 <= number <= len(tasks):This makes sure the requested task number is within the valid range and avoids an IndexError for out-of-range numbers.
5. Keeping the menu running
The while True loop keeps showing the menu.
When the user selects option 5, this code runs:
case "5":
print("Goodbye!")
breakThe break statement exits the loop. Remember, match-case selects an action, but it doesn’t repeat the menu by itself.
6. Handling empty input
We use strip() to remove spaces from the beginning and end of the user’s input.
For example, an input containing only spaces becomes an empty string:
task = input("Enter the task: ").strip()Then we check whether the task is empty:
if task == "":
print("A task can't be empty.")We also check whether the list is empty before trying to update or remove a task.
Common Mistake: Reassigning the List Inside a Function
Consider this version of add_task():
def add_task(tasks, task):
tasks = tasks + [task]You might expect this to add a task to the original list, but it doesn’t.
The + operator creates a new list. The name tasks inside the function then refers to that new list, while the original list outside the function remains unchanged.
That’s why our program uses:
def add_task(tasks, task):
tasks.append(task)append() modifies the existing list directly.
One Limitation
The program works for the inputs we’ve handled, but there are still a few things to improve.
1. Tasks aren’t saved permanently.
The tasks exist only in memory, so they disappear when the program ends. We’ll learn how to save them when we reach file handling.
2. Entering letters for a task number causes an error.
For example, if the program asks for a task number and the user enters "hello", int() raises a ValueError.
We’ll learn how to handle this properly when we reach error handling.
Challenges
If you want to go further, try these:
- Add an option that shows how many tasks are in the list using
len(). - Add an option that sorts the tasks alphabetically.
- Add an option that removes all tasks using
clear(). - Add a
“Mark as done”option. Hint: you could add"[done] "in front of the task text.
👉 Next tutorial: Python Tuples