-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_manager.py
More file actions
199 lines (163 loc) · 5.6 KB
/
task_manager.py
File metadata and controls
199 lines (163 loc) · 5.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#importing the json module
import json
#importing the os module
import os
#creating an empty list to store tasks
tasks = []
#constant for the filename where we save tasks
TASKS_FILE = "tasks.json"
def display_header():
"""Displays the header of the task manager."""
print("="*40)
print(" PERSONAL TASK MANAGER ")
print("="*40)
def display_menu():
"""Displays the main menu options."""
print("\n--- Main Menu ---")
print("1. Add a new task")
print("2. View all tasks")
print("3. Mark task as complete")
print("4. Delete a task")
print("5. Save and exit")
print("-" * 20)
def add_task():
"""
Add a new task to the task list.
"""
description = input("Enter the task description: ")
#Validate input and also strip whitespace
if not description.strip():
print("Task description cannot be empty.")
return #break out of the function if input is valid
task = {
"description": description.strip(),
"completed": False, #New tasks start incomplete
"id": len(tasks) + 1 #Assign a simple unique ID to each task
}
#Append the new task to the tasks list
tasks.append(task)
#print confirmation message
print(f"Task added successfully (ID: {task['id']})")
def view_tasks():
"""
Displays all tasks in the task list, including the task ID, description, and status.
"""
#Check if the tasks list is empty
if not tasks:
print("No tasks available.")
return
#Print header
print("\n--- Your Tasks ---")
#enumerate() to get index and task
#we start index from 1 for user-friendliness
for index, task in enumerate(tasks, start=1):
#Get values from the task dictionary using the keys
task_id = task["id"]
description = task["description"]
is_completed = task["completed"]
# Ternary operator: value_if_true if condition else value_if_false
status = "✓" if is_completed else " "
print(f"{index}. [{status}] {description} (ID: {task_id})")
#print summary
#sum() adds up al the True values in the list (True counts as 1 and False as 0)
completed_count = sum(task["completed"] for task in tasks)
total_count = len(tasks)
print(f"\nCompleted: {completed_count} / {total_count} tasks")
def mark_complete():
"""
Mark a task as complete.
User selects task by ID.
"""
view_tasks() #Show current tasks
#if no tasks, return
if not tasks:
return
#prompt user for task ID
#Validate that input is a number
try:
task_id = int(input("\nEnter the ID of the task to mark as complete: "))
except ValueError:
print("Invalid input. Please enter a valid number")
return
#Find the task with the given ID
for task in tasks:
if task["id"] == task_id:
#Found the task, mark it complete
task["completed"] = True
print(f"✓ {task_id} marked as complete.")
return #Exit the function after marking complete
print(f"No task found with ID: {task_id}")
def delete_task():
"""
Delete a task from the task list.
User selects task by ID.
"""
view_tasks() #Show current tasks
#if no tasks, return
if not tasks:
return
#prompt user for task ID
#Validate that input is a number
try:
task_id = int(input("\nEnter the ID of the task to delete: "))
except ValueError:
print("Invalid input. Please enter a valid number")
return
#Find the task with the given ID and remove it
for task in tasks:
if task["id"] == task_id:
tasks.remove(task)
print(f"Task ID {task_id} deleted successfully.")
return #Exit the function after deletion
print(f"No task found with ID: {task_id}")
def save_tasks():
"""
Save the current tasks to a JSON file.
"""
with open(TASKS_FILE, "w") as file:
json.dump(tasks, file, indent=2)
print(f"Tasks saved to {TASKS_FILE} successfully.")
def load_tasks():
"""
Load tasks from a JSON file.
"""
#modifying the global tasks variable to update it
global tasks
#Check if the file exists before trying to open it
if os.path.exists(TASKS_FILE):
try:
with open(TASKS_FILE, "r") as file:
tasks = json.load(file)
print(f" {len(tasks)} task(s)loaded from {TASKS_FILE} successfully.")
except json.JSONDecodeError:
print(f"Error: {TASKS_FILE} is corrupted or not in valid JSON format.")
print("Starting afresh")
tasks = []
else:
#file does not exist
print(f"No existing task file found. Starting with an empty task list.")
def main():
"""
Main function to run the task manager.
"""
display_header()
load_tasks() #Load tasks at startup
while True:
display_menu()
choice = input("Enter your choice (1-5): ")
if choice == "1":
add_task()
elif choice == "2":
view_tasks()
elif choice == "3":
mark_complete()
elif choice == "4":
delete_task()
elif choice == "5":
save_tasks()
print("\nYour tasks have been saved. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")
if __name__ == "__main__":
main()