w3resource

Python - Build a basic To-Do List Project: Solutions and Explanations


To-Do List Application:

Build a basic to-do list application where users can add, edit, and delete tasks.

Input values:
User interacts with the application through commands to add, edit, or delete tasks.

Output value:

Updated the to-do list based on user actions.

Example:

Input values:
1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 1
Enter task: Buy groceries
Output value:
Task added successfully.
Input values:
1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 2
Enter task index to edit: 1
Enter new task: Buy weekly groceries
Output value:
Task edited successfully.
Input values:
1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 3
Enter task index to delete: 1
Output value:
Task deleted successfully.
Input values:
1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 4

Here are two different solutions for a basic to-do list application in Python. This application will allow users to add, edit, and delete tasks using a command-line interface.

Solution 1: Basic Approach Using a While Loop and List Operations

Code:

# Solution 1: Basic Approach Using a While Loop and List Operations

# Initialize an empty list to store tasks
tasks = []

# Function to display the available options
def display_menu():
    print("\n1. Add Task")
    print("2. Edit Task")
    print("3. Delete Task")
    print("4. Exit")

# Start an infinite loop to continuously interact with the user
while True:
    # Display the menu options
    display_menu()
    
    # Get the user's choice
    choice = input("Select an option: ")

    # Option 1: Add Task
    if choice == '1':
        # Prompt the user to enter a task
        task = input("Enter task: ")
        # Add the task to the list
        tasks.append(task)
        print("Task added successfully.")

    # Option 2: Edit Task
    elif choice == '2':
        # Check if there are tasks available to edit
        if tasks:
            # Display the current tasks with their indices
            for index, task in enumerate(tasks):
                print(f"{index + 1}. {task}")
            # Prompt the user to enter the index of the task to edit
            try:
                task_index = int(input("Enter task index to edit: ")) - 1
                # Check if the entered index is valid
                if 0 <= task_index < len(tasks):
                    # Prompt the user to enter a new task
                    new_task = input("Enter new task: ")
                    # Update the task at the specified index
                    tasks[task_index] = new_task
                    print("Task edited successfully.")
                else:
                    print("Invalid index.")
            except ValueError:
                print("Please enter a valid number.")
        else:
            print("No tasks available to edit.")

    # Option 3: Delete Task
    elif choice == '3':
        # Check if there are tasks available to delete
        if tasks:
            # Display the current tasks with their indices
            for index, task in enumerate(tasks):
                print(f"{index + 1}. {task}")
            # Prompt the user to enter the index of the task to delete
            try:
                task_index = int(input("Enter task index to delete: ")) - 1
                # Check if the entered index is valid
                if 0 <= task_index < len(tasks):
                    # Remove the task at the specified index
                    tasks.pop(task_index)
                    print("Task deleted successfully.")
                else:
                    print("Invalid index.")
            except ValueError:
                print("Please enter a valid number.")
        else:
            print("No tasks available to delete.")

    # Option 4: Exit
    elif choice == '4':
        # Exit the application
        print("Exiting the application. Goodbye!")
        break

    # Handle invalid menu choices
    else:
        print("Invalid choice. Please select a valid option.")

Output:

1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 1
Enter task: Buy daily groceries
Task added successfully.

1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 2
1. Buy daily groceries
Enter task index to edit: 1
Enter new task: Buy weekly groceries
Task edited successfully.

1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 3
1. Buy weekly groceries
Enter task index to delete: 1
Task deleted successfully.

1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 4
Exiting the application. Goodbye!

Explanation:

  • Uses a simple list ('tasks') to store tasks and a 'while' loop to provide a continuous menu-driven interface.
  • Contains menu options for adding, editing, and deleting tasks.
  • Utilizes basic list operations ('append', 'pop', and direct indexing) to manage tasks.
  • Handles user input and errors with simple conditionals.
  • This approach is straightforward but less organized as the code grows.

Solution 2: Using a Class to Encapsulate the To-Do List Functionality

Code:

# Solution 2: Using a Class to Encapsulate the To-Do List Functionality

class ToDoList:
    """Class to handle to-do list operations"""

    def __init__(self):
        # Initialize an empty list to store tasks
        self.tasks = []

    def display_menu(self):
        """Display menu options to the user"""
        print("\n1. Add Task")
        print("2. Edit Task")
        print("3. Delete Task")
        print("4. Exit")

    def add_task(self):
        """Add a new task to the list"""
        task = input("Enter task: ")
        self.tasks.append(task)
        print("Task added successfully.")

    def edit_task(self):
        """Edit an existing task"""
        if self.tasks:
            self.display_tasks()
            try:
                task_index = int(input("Enter task index to edit: ")) - 1
                if 0 <= task_index < len(self.tasks):
                    new_task = input("Enter new task: ")
                    self.tasks[task_index] = new_task
                    print("Task edited successfully.")
                else:
                    print("Invalid index.")
            except ValueError:
                print("Please enter a valid number.")
        else:
            print("No tasks available to edit.")

    def delete_task(self):
        """Delete a task from the list"""
        if self.tasks:
            self.display_tasks()
            try:
                task_index = int(input("Enter task index to delete: ")) - 1
                if 0 <= task_index < len(self.tasks):
                    self.tasks.pop(task_index)
                    print("Task deleted successfully.")
                else:
                    print("Invalid index.")
            except ValueError:
                print("Please enter a valid number.")
        else:
            print("No tasks available to delete.")

    def display_tasks(self):
        """Display all tasks with their indices"""
        for index, task in enumerate(self.tasks):
            print(f"{index + 1}. {task}")

    def run(self):
        """Run the to-do list application"""
        while True:
            self.display_menu()
            choice = input("Select an option: ")

            if choice == '1':
                self.add_task()
            elif choice == '2':
                self.edit_task()
            elif choice == '3':
                self.delete_task()
            elif choice == '4':
                print("Exiting the application. Goodbye!")
                break
            else:
                print("Invalid choice. Please select a valid option.")


# Create an instance of the ToDoList class and run the application
todo_list = ToDoList()
todo_list.run()

Output:

1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 1
Enter task: Buy daily groceries
Task added successfully.

1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 2
1. Buy daily groceries
Enter task index to edit: Buy weekly groceries
Please enter a valid number.

1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 3
1. Buy daily groceries
Enter task index to delete: 1
Task deleted successfully.

1. Add Task
2. Edit Task
3. Delete Task
4. Exit
Select an option: 4
Exiting the application. Goodbye!

Explanation:

  • Uses a 'ToDoList' class to encapsulate all functionality related to the to-do list, making the code modular and easy to maintain.
  • The class has methods for adding ('add_task'), editing ('edit_task'), deleting ('delete_task'), and displaying tasks ('display_tasks').
  • The 'run' method manages the application's main loop, calling other methods as needed.
  • This approach is more organized and makes the code easier to extend and maintain by leveraging Object-Oriented Programming (OOP) principles.

Note:
Both solutions achieve the required functionality for a to-do list application, but Solution 2 provides a more modular, organized, and scalable structure by using OOP principles.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/projects/python/python-to-do-list-application-project.php