0% found this document useful (0 votes)
6 views

todo-PYTHON

Uploaded by

vilyxu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

todo-PYTHON

Uploaded by

vilyxu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

import json

from datetime import datetime

class Task:
"""
A class to represent a single task.
"""
def __init__(self, title, priority, deadline, description=""):
self.title = title
self.priority = priority
self.deadline = deadline
self.description = description
self.completed = False

def mark_completed(self):
"""
Mark the task as completed.
"""
self.completed = True

def to_dict(self):
"""
Convert task to a dictionary for saving to a file.
"""
return {
"title": self.title,
"priority": self.priority,
"deadline": self.deadline,
"description": self.description,
"completed": self.completed
}

@staticmethod
def from_dict(data):
"""
Create a Task object from a dictionary.
"""
task = Task(data['title'], data['priority'], data['deadline'],
data['description'])
task.completed = data['completed']
return task

def __str__(self):
"""
String representation of the task.
"""
status = "✅" if self.completed else "❌"
return f"[{status}] {self.title} (Priority: {self.priority}, Deadline:
{self.deadline})\n {self.description}"

class ToDoList:
"""
A class to manage a collection of tasks.
"""
def __init__(self):
self.tasks = []
def add_task(self, task):
"""
Add a new task to the list.
"""
self.tasks.append(task)

def remove_task(self, title):


"""
Remove a task by its title.
"""
self.tasks = [task for task in self.tasks if task.title != title]

def mark_task_completed(self, title):


"""
Mark a task as completed by its title.
"""
for task in self.tasks:
if task.title == title:
task.mark_completed()
return True
return False

def view_tasks(self, sort_by="priority"):


"""
View tasks, sorted by priority or deadline.
"""
if sort_by == "priority":
sorted_tasks = sorted(self.tasks, key=lambda t: t.priority)
elif sort_by == "deadline":
sorted_tasks = sorted(self.tasks, key=lambda t:
datetime.strptime(t.deadline, "%Y-%m-%d"))
else:
sorted_tasks = self.tasks

for task in sorted_tasks:


print(task)

def save_to_file(self, filename):


"""
Save tasks to a JSON file.
"""
with open(filename, "w") as f:
json.dump([task.to_dict() for task in self.tasks], f, indent=4)

def load_from_file(self, filename):


"""
Load tasks from a JSON file.
"""
try:
with open(filename, "r") as f:
data = json.load(f)
self.tasks = [Task.from_dict(item) for item in data]
except FileNotFoundError:
print(f"File '{filename}' not found. Starting with an empty to-do
list.")

def __str__(self):
"""
String representation of the to-do list.
"""
return "\n".join(str(task) for task in self.tasks)

def display_menu():
"""
Display the menu of options.
"""
print("\n--- To-Do List Menu ---")
print("1. Add Task")
print("2. View Tasks")
print("3. Mark Task as Completed")
print("4. Delete Task")
print("5. Save Tasks to File")
print("6. Load Tasks from File")
print("7. Exit")

def get_task_from_user():
"""
Get task details from the user.
"""
title = input("Enter task title: ")
priority = int(input("Enter priority (1 = High, 3 = Low): "))
deadline = input("Enter deadline (YYYY-MM-DD): ")
description = input("Enter task description (optional): ")
return Task(title, priority, deadline, description)

def main():
"""
Main function to run the to-do list application.
"""
todo_list = ToDoList()
print("Welcome to the To-Do List Manager!")

while True:
display_menu()
choice = input("Choose an option: ")

if choice == "1":
print("\n--- Add Task ---")
task = get_task_from_user()
todo_list.add_task(task)
print("Task added successfully!")
elif choice == "2":
print("\n--- View Tasks ---")
sort_option = input("Sort by 'priority' or 'deadline': ")
todo_list.view_tasks(sort_option)
elif choice == "3":
print("\n--- Mark Task as Completed ---")
title = input("Enter the title of the task to mark as completed: ")
if todo_list.mark_task_completed(title):
print("Task marked as completed!")
else:
print("Task not found.")
elif choice == "4":
print("\n--- Delete Task ---")
title = input("Enter the title of the task to delete: ")
todo_list.remove_task(title)
print("Task deleted successfully!")
elif choice == "5":
print("\n--- Save Tasks to File ---")
filename = input("Enter filename to save tasks: ")
todo_list.save_to_file(filename)
print(f"Tasks saved to '{filename}'!")
elif choice == "6":
print("\n--- Load Tasks from File ---")
filename = input("Enter filename to load tasks: ")
todo_list.load_from_file(filename)
print(f"Tasks loaded from '{filename}'!")
elif choice == "7":
print("Exiting To-Do List Manager. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

You might also like