Skip to content

Commit 5c7113f

Browse files
authored
Update to_do_app.py
1 parent f999c2e commit 5c7113f

1 file changed

Lines changed: 131 additions & 0 deletions

File tree

To-do List/to_do_app.py

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,132 @@
11

2+
"""
3+
To-Do List App
4+
--------------------
5+
A simple command-line Python app that lets you:
6+
1. Add new tasks
7+
2. View all tasks
8+
3. Mark tasks as completed
9+
4. Delete tasks
10+
5. Exit the app
11+
12+
All tasks are stored in a local text file (tasks.txt) so that data persists between sessions.
13+
This is a beginner-friendly example of file handling, loops, and user interaction.
14+
"""
15+
16+
# ---------- Import Section ----------
17+
import os # Used to check if the file exists before reading/writing
18+
19+
20+
# ---------- Function Definitions ----------
21+
22+
def load_tasks():
23+
"""Reads all tasks from the file and returns them as a list of dictionaries."""
24+
tasks = []
25+
if os.path.exists("tasks.txt"):
26+
with open("tasks.txt", "r") as file:
27+
for line in file:
28+
# Each line has the format: task_name|completed_status
29+
name, status = line.strip().split("|")
30+
tasks.append({"name": name, "completed": status == "True"})
31+
return tasks
32+
33+
34+
def save_tasks(tasks):
35+
"""Saves all tasks to the file so data is persistent."""
36+
with open("tasks.txt", "w") as file:
37+
for task in tasks:
38+
file.write(f"{task['name']}|{task['completed']}\n")
39+
40+
41+
def show_tasks(tasks):
42+
"""Displays all tasks with their status."""
43+
if not tasks:
44+
print("\n✅ No tasks found. Start by adding one!\n")
45+
return
46+
print("\nYour To-Do List:")
47+
print("-" * 30)
48+
for i, task in enumerate(tasks, start=1):
49+
status = "✔️" if task["completed"] else "❌"
50+
print(f"{i}. {task['name']} [{status}]")
51+
print("-" * 30)
52+
53+
54+
def add_task(tasks):
55+
"""Takes input from the user and adds a new task to the list."""
56+
name = input("Enter new task: ").strip()
57+
if name:
58+
tasks.append({"name": name, "completed": False})
59+
save_tasks(tasks)
60+
print(f"✅ Task '{name}' added successfully!")
61+
else:
62+
print("⚠️ Task name cannot be empty!")
63+
64+
65+
def mark_task_completed(tasks):
66+
"""Marks a selected task as completed."""
67+
show_tasks(tasks)
68+
if not tasks:
69+
return
70+
try:
71+
task_num = int(input("Enter the task number to mark completed: "))
72+
if 1 <= task_num <= len(tasks):
73+
tasks[task_num - 1]["completed"] = True
74+
save_tasks(tasks)
75+
print(f"🎉 Task '{tasks[task_num - 1]['name']}' marked as completed!")
76+
else:
77+
print("⚠️ Invalid task number.")
78+
except ValueError:
79+
print("⚠️ Please enter a valid number.")
80+
81+
82+
def delete_task(tasks):
83+
"""Deletes a selected task from the list."""
84+
show_tasks(tasks)
85+
if not tasks:
86+
return
87+
try:
88+
task_num = int(input("Enter the task number to delete: "))
89+
if 1 <= task_num <= len(tasks):
90+
deleted = tasks.pop(task_num - 1)
91+
save_tasks(tasks)
92+
print(f"🗑️ Task '{deleted['name']}' deleted successfully!")
93+
else:
94+
print("⚠️ Invalid task number.")
95+
except ValueError:
96+
print("⚠️ Please enter a valid number.")
97+
98+
99+
def main():
100+
"""Main program loop that runs until the user exits."""
101+
tasks = load_tasks()
102+
103+
while True:
104+
print("""
105+
========= TO-DO LIST MENU =========
106+
1. View all tasks
107+
2. Add a new task
108+
3. Mark a task as completed
109+
4. Delete a task
110+
5. Exit
111+
===================================
112+
""")
113+
choice = input("Enter your choice (1-5): ").strip()
114+
115+
if choice == "1":
116+
show_tasks(tasks)
117+
elif choice == "2":
118+
add_task(tasks)
119+
elif choice == "3":
120+
mark_task_completed(tasks)
121+
elif choice == "4":
122+
delete_task(tasks)
123+
elif choice == "5":
124+
print("👋 Exiting To-Do List. Goodbye!")
125+
break
126+
else:
127+
print("⚠️ Invalid choice. Please enter a number between 1 and 5.")
128+
129+
130+
# ---------- Run the App ----------
131+
if __name__ == "__main__":
132+
main()

0 commit comments

Comments
 (0)