Categories We Write About

Build a Python script to manage to-do lists

Here’s a comprehensive Python script to manage to-do lists with essential features like adding, viewing, updating, and deleting tasks. It uses simple file storage (JSON) to persist data between runs.

python
import json import os TODO_FILE = "todo_list.json" def load_tasks(): if not os.path.exists(TODO_FILE): return [] with open(TODO_FILE, "r") as f: return json.load(f) def save_tasks(tasks): with open(TODO_FILE, "w") as f: json.dump(tasks, f, indent=4) def show_tasks(tasks): if not tasks: print("No tasks in your to-do list.") return print("nYour To-Do List:") for idx, task in enumerate(tasks, 1): status = "✓" if task["completed"] else "✗" print(f"{idx}. [{status}] {task['task']}") def add_task(tasks): task_desc = input("Enter the task description: ").strip() if task_desc: tasks.append({"task": task_desc, "completed": False}) print("Task added.") else: print("Task description cannot be empty.") def mark_task_completed(tasks): show_tasks(tasks) try: task_num = int(input("Enter the task number to mark as completed: ")) if 1 <= task_num <= len(tasks): tasks[task_num - 1]["completed"] = True print("Task marked as completed.") else: print("Invalid task number.") except ValueError: print("Please enter a valid number.") def delete_task(tasks): show_tasks(tasks) try: task_num = int(input("Enter the task number to delete: ")) if 1 <= task_num <= len(tasks): deleted = tasks.pop(task_num - 1) print(f"Deleted task: {deleted['task']}") else: print("Invalid task number.") except ValueError: print("Please enter a valid number.") def main(): tasks = load_tasks() while True: print("nOptions:") print("1. View tasks") print("2. Add task") print("3. Mark task as completed") print("4. Delete task") print("5. Exit") choice = input("Choose an option (1-5): ").strip() if choice == '1': show_tasks(tasks) elif choice == '2': add_task(tasks) save_tasks(tasks) elif choice == '3': mark_task_completed(tasks) save_tasks(tasks) elif choice == '4': delete_task(tasks) save_tasks(tasks) elif choice == '5': print("Goodbye!") break else: print("Invalid option, please try again.") if __name__ == "__main__": main()

This script allows you to:

  • Add new tasks

  • View all tasks with completion status

  • Mark tasks as completed

  • Delete tasks

  • Save tasks persistently in a JSON file

Run this in a terminal, and it will manage your to-do list interactively.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About