Welcome back! In this section, we'll dive into implementing the core features of our To-Do list application: adding new tasks, viewing existing tasks, and marking tasks as completed. We'll build these functionalities step-by-step, making sure each part is understandable.
First, let's think about how we'll store our to-do items. A list is a natural choice in Python. Each item in the list will represent a single to-do task. For now, we'll keep it simple and each task will be a string. Later, we might want to store more information, like a due date or a priority, which would lead us to use dictionaries or custom objects within our list.
todo_list = []Now, let's create a function to add new tasks. This function will take the task description as input and append it to our todo_list. It's good practice to give functions descriptive names so we know exactly what they do.
def add_task(task_description):
todo_list.append(task_description)
print(f"Added: '{task_description}'")Next, we need a way to see all the tasks we've added. A function to display the list will iterate through each item and print it. We should also consider how to present the tasks to the user. Showing them with a number makes it easier to refer to them later, especially when we want to mark them as done.
def view_tasks():
if not todo_list:
print("Your to-do list is empty!")
else:
print("\n--- Your To-Do List ---")
for index, task in enumerate(todo_list):
print(f"{index + 1}. {task}")
print("-----------------------\n")Finally, let's implement the functionality to mark a task as done. This is a bit more involved. We'll need to know which task the user wants to mark, so we'll ask for its number. We'll then remove that task from our list. We should also handle cases where the user enters an invalid number (e.g., a number that's not in the list, or not a number at all).