forked from fineanmol/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo.py
More file actions
104 lines (91 loc) · 2.75 KB
/
todo.py
File metadata and controls
104 lines (91 loc) · 2.75 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
import json
import os
DATA_FILE = "tasks.json"
def load_tasks():
if not os.path.exists(DATA_FILE):
return []
try:
with open(DATA_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, OSError):
return []
def save_tasks(tasks):
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(tasks, f, ensure_ascii=False, indent=2)
def list_tasks(tasks):
if not tasks:
print("No tasks.")
return
for i, t in enumerate(tasks, 1):
status = "✔" if t["done"] else "✗"
print(f"{i}. [{status}] {t['title']}")
def add_task(tasks, title):
title = title.strip()
if not title:
print("Title cannot be empty.")
return
tasks.append({"title": title, "done": False})
save_tasks(tasks)
print("Added.")
def toggle_task(tasks, index):
if index < 1 or index > len(tasks):
print("Invalid task number.")
return
tasks[index - 1]["done"] = not tasks[index - 1]["done"]
save_tasks(tasks)
print("Updated.")
def delete_task(tasks, index):
if index < 1 or index > len(tasks):
print("Invalid task number.")
return
tasks.pop(index - 1)
save_tasks(tasks)
print("Deleted.")
def help_menu():
print("Commands:")
print(" list Show tasks")
print(" add <title> Add a task")
print(" done <num> Toggle done/undone")
print(" del <num> Delete a task")
print(" help Show this help")
print(" quit Exit")
def main():
tasks = load_tasks()
print("Simple To-Do List")
help_menu()
while True:
try:
cmd = input("> ").strip()
except (EOFError, KeyboardInterrupt):
print("\nBye!")
break
if not cmd:
continue
parts = cmd.split(maxsplit=1)
action = parts[0].lower()
if action == "list":
list_tasks(tasks)
elif action == "add":
if len(parts) == 1:
print("Usage: add <title>")
else:
add_task(tasks, parts[1])
elif action == "done":
if len(parts) == 1 or not parts[1].isdigit():
print("Usage: done <num>")
else:
toggle_task(tasks, int(parts[1]))
elif action == "del":
if len(parts) == 1 or not parts[1].isdigit():
print("Usage: del <num>")
else:
delete_task(tasks, int(parts[1]))
elif action == "help":
help_menu()
elif action == "quit":
print("Bye!")
break
else:
print("Unknown command. Type 'help'.")
if __name__ == "__main__":
main()