Menu Close

Building a Simple To-Do List Application in Python

Rate this post

In this blog, we will walk through the process of creating a simple to-do list application in Python. This application allows users to add, update, delete, and view tasks, as well as save tasks to a file and load them upon starting the application. We’ll explain each function used in the project and provide the complete code at the end.

Introduction

A to-do list application is a great project for beginners to practice their Python programming skills. It involves working with lists, file I/O operations, and user input handling. By the end of this blog, you’ll have a fully functional command-line to-do list application.

Functions Overview

show_tasks

def show_tasks(tasks):
    if not tasks:
        print("No tasks found.")
    else:
        for i, task in enumerate(tasks, 1):
            print(f"{i}. {task}")

The show_tasks function displays all the tasks in the list. If the list is empty, it informs the user that no tasks are found. Otherwise, it prints each task with an index number.

add_task

def add_task(tasks, new_task):
    tasks.append(new_task)
    print("Task Added Successfully.")

The add_task function appends a new task to the list and confirms to the user that the task was added successfully.

update_task

def update_task(tasks, index, updated_task):
    if 1 <= index <= len(tasks):
        tasks[index - 1] = updated_task
        print("Task Updated Successfully")
    else:
        print("Invalid Task Index.")

The update_task function updates an existing task based on its index. It checks if the provided index is valid before updating the task. If the index is invalid, it notifies the user.

delete_task

def delete_task(tasks, index):
    if 1 <= index <= len(tasks):
        deleted_task = tasks.pop(index - 1)
        print(f"Task '{deleted_task}' deleted Successfully")
    else:
        print("Invalid Task Index.")

The delete_task function removes a task from the list based on its index. It ensures the index is valid before deleting the task and confirms the deletion to the user.

save_task_to_file

def save_task_to_file(file_path, tasks):
    with open(file_path, "w") as file:
        for task in tasks:
            file.write(f"{task}\n")

The save_task_to_file function saves all tasks to a specified file. It writes each task on a new line in the file.

load_tasks_from_file

def load_tasks_from_file(file_path):
    tasks = []
    if os.path.exists(file_path):
        with open(file_path, "r") as file:
            tasks = file.read().splitlines()
    return tasks

The load_tasks_from_file function loads tasks from a specified file if it exists. It reads each line of the file and adds it to the tasks list.

Main Program Logic

def main():
    file_path = "todo_list.txt"
    tasks = load_tasks_from_file(file_path)
    while True:
        print("\n===== To-Do List =====")
        print("1. Show Tasks")
        print("2. Add Tasks")
        print("3. Update Tasks")
        print("4. Delete Tasks")
        print("5. Save and Exit")
        choice = input("Enter your choice (1-5): ")
        if choice == "1":
            show_tasks(tasks)
        elif choice == "2":
            new_task = input("Enter the task to add: ")
            add_task(tasks, new_task)
        elif choice == "3":
            index = int(input("Enter the task index to update: "))
            updated_task = input("Enter the updated task: ")
            update_task(tasks, index, updated_task)
        elif choice == "4":
            index = int(input("Enter the task index to delete: "))
            delete_task(tasks, index)
        elif choice == "5":
            save_task_to_file(file_path, tasks)
            print("Tasks saved. Exiting..")
            break
        else:
            print("Invalid choice. Please try again.")

The main function is the core of the application. It handles user interactions and calls the appropriate functions based on the user’s choice. It also ensures that tasks are loaded from a file at the start and saved to the file before exiting.

Complete Code

Here is the complete code for the to-do list application:

import os

def show_tasks(tasks):
    if not tasks:
        print("No tasks found.")
    else:
        for i, task in enumerate(tasks, 1):
            print(f"{i}. {task}")

def add_task(tasks, new_task):
    tasks.append(new_task)
    print("Task Added Successfully.")

def update_task(tasks, index, updated_task):
    if 1 <= index <= len(tasks):
        tasks[index - 1] = updated_task
        print("Task Updated Successfully")
    else:
        print("Invalid Task Index.")

def delete_task(tasks, index):
    if 1 <= index <= len(tasks):
        deleted_task = tasks.pop(index - 1)
        print(f"Task '{deleted_task}' deleted Successfully")
    else:
        print("Invalid Task Index.")

def save_task_to_file(file_path, tasks):
    with open(file_path, "w") as file:
        for task in tasks:
            file.write(f"{task}\n")

def load_tasks_from_file(file_path):
    tasks = []
    if os.path.exists(file_path):
        with open(file_path, "r") as file:
            tasks = file.read().splitlines()
    return tasks

def main():
    file_path = "todo_list.txt"
    tasks = load_tasks_from_file(file_path)
    while True:
        print("\n===== To-Do List =====")
        print("1. Show Tasks")
        print("2. Add Tasks")
        print("3. Update Tasks")
        print("4. Delete Tasks")
        print("5. Save and Exit")
        choice = input("Enter your choice (1-5): ")
        if choice == "1":
            show_tasks(tasks)
        elif choice == "2":
            new_task = input("Enter the task to add: ")
            add_task(tasks, new_task)
        elif choice == "3":
            index = int(input("Enter the task index to update: "))
            updated_task = input("Enter the updated task: ")
            update_task(tasks, index, updated_task)
        elif choice == "4":
            index = int(input("Enter the task index to delete: "))
            delete_task(tasks, index)
        elif choice == "5":
            save_task_to_file(file_path, tasks)
            print("Tasks saved. Exiting..")
            break
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main()

By following this blog, you’ve built a simple yet functional to-do list application in Python. This project demonstrates basic list operations, file handling, and user interaction in a command-line interface.

Conclusion:

This tutorial exemplifies the power of Python libraries in creating practical solutions. Whether you’re a developer honing your skills or an individual seeking personalized task management, this guide offers a solid starting point. Moving forward, feel free to explore further customization and feature additions to tailor the app to your specific needs. With creativity and innovation, the potential for enhancement is limitless.

If you have any queries related to this article, then you can ask in the comment section, we will contact you soon, and Thank you for reading this article.

Follow me to receive more useful content:

Instagram | Twitter | Linkedin | Youtube

Thank you

Suggested Blog Posts

Leave a Reply

Your email address will not be published.