How to create a To-Do list in python

               Planning is very important for any task management. Let us create a To-Do list using python.

Steps to follow:

  • ·       This program starts with importing a built-in  file ‘os’.
  • ·       F_NAME is the file name. it is assigned with a txt file name.
  • ·       There are three functions. ‘load_it()’,’save_it()’,’show_it()’.
  • ·       ‘load_it()’ opens the file if exists. Otherwise, it displays the error message.
  • ·       ‘save_it()’ opens the file and writes the content which was given by user.
  • ·       ‘show_it()’ displays the todo list tasks.
  • ·       ‘main()’ function displays the options. Based on the user preference, the data is read,write and display accordingly.

Code:

import os

F_NAME = "todolist.txt"

def load_it():

    if os.path.exists(F_NAME):

        with open(F_NAME, "r") as f:

            return [line.strip() for line in f.readlines()]

    return []

def save_it(tasks):

    with open(F_NAME, "w") as f:

        for task in tasks:

            f.write(task + "\n")

def show_it(tasks):

    if not tasks:

        print("No tasks yet!")

    else:

        print("\nHere is the To-Do List:")

        for i, task in enumerate(tasks, 1):

            print(f"{i}. {task}")

def main():

    tasks = load_it()

    while True:

        print("\nOptions: [1] Add [2] Remove [3] Show [4] Exit")

        choice = input("Choose: ")

        if choice == "1":

            task = input("Enter new task: ")

            tasks.append(task)

            save_it(tasks)

          elif choice == "2":

            num = int(input("Enter the task number to remove: "))

            if 0 < num <= len(tasks):

                tasks.pop(num-1)

                save_it(tasks)

        elif choice == "3":

          show_it(tasks)

        elif choice == "4":

            print("Thank you for choosing the app")

            break

        else:

            print("Invalid choice!")

if __name__ == "__main__":

    main()

Output:

C:\raji\blog>py todo.py

Options: [1] Add [2] Remove [3] Show [4] Exit

Choose: 1

Enter new task: repeat

Options: [1] Add [2] Remove [3] Show [4] Exit

Choose: 3

Here is the To-Do List:

1. plan

2. design

3. proceed

4. execute

5. test

6. repeat

Options: [1] Add [2] Remove [3] Show [4] Exit

Choose: 2

Enter the task number to remove: 6

Options: [1] Add [2] Remove [3] Show [4] Exit

Choose: 3

Here is the To-Do List:

1. plan

2. design

3. proceed

4. execute

5. test

Options: [1] Add [2] Remove [3] Show [4] Exit

Choose: 4

Thank you for choosing the app

Thus, the python program to implement a Todo list was done successfully. Hope, this code is useful to you. Keep coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Callables in Multithreading