Python Projects for Beginners
How to build To Do List App in Python
An application called a " To do list app " is made to help users in managing, tracking, and organizing their tasks. Users can make a to-do list, prioritize it, add deadlines, mark it as finished, and occasionally even schedule reminders. Applications for to-do lists are frequently used for time management, project management, and personal productivity.
Key Features of a To-Do List Application
- Task Creation: In this feature users can add tasks, descriptions, due dates, and priorities.
- Task Management: Users can add, edit, delete, or mark tasks as completed.
- Prioritization: Tasks can be set priority levels like High, Medium, Low to help users focus on what’s important.
- Due Dates: Users have to set deadlines for tasks to ensure timely completion.
- Reminders: Notifications or reminders can be set to alert users about tasks.
- Sorting and Filtering: Tasks can be sorted or filtered by using due date, priority, or completion status.
- Search Functionality: Users can use this feature to search for specific tasks by name or keyword.
- Persistence: Tasks can be saved so they persist even after the application is closed.
- User Interface: A clean and intuitive interface is used (command-line or graphical) for easy interaction.
Why Use a To-Do List Application?
- Improved Productivity: It helps users stay organized and focused on their goals.
- Time Management: Time management allows users to allocate time effectively by prioritizing tasks.
- Reduced Stress: It helps to keep track of tasks so users don’t forget important deadlines.
- Progress Tracking: Users can know about what they’ve accomplished and what’s left to do.
Types of To-Do List Applications
Simple To-Do Lists:
Basic applications that allow users to add and check off tasks.
Example: A sticky note or a basic mobile app.
Advanced Task Managers:
Include due dates, priorities, reminders, and collaboration.
Example: Todoist, Microsoft To-Do, or Trello.
Project Management Tools:
It is decorated for teams and complex projects with features like task dependencies, timelines, and collaboration.
Example: Asana, Jira, or Monday.com.
Custom-Built Applications:
This can be made to specific needs, often built by individuals or organizations.
Example: The Python-based To-Do List application we’re building.
Example Use Cases
Personal Use: User can manage daily chores, grocery lists, or personal goals.
Work/Professional Use: The users can track work assignments, organise meeting deadlines, and to manage projects.
Academic Use: The user can keep track of homework, exams, and study schedules.
Team Collaboration: The team assigned tasks to team members and to track progress.
Step 1: Set Up the Project
Create a new directory for your project:
Python Code
mkdir todo-app
cd todo-app
Save and Open todo.py in your favorite text editor or IDE and add the following code:
Python Code
# todo.py
import json
from datetime import datetime, timedelta
# File to store tasks
TASKS_FILE = "tasks.json"
# Initialize an empty list to store tasks
tasks = []
# Function to load tasks from a file
def load_tasks():
try:
with open(TASKS_FILE, "r") as file:
return json.load(file)
except FileNotFoundError:
return []
# Function to save tasks to a file
def save_tasks():
with open(TASKS_FILE, "w") as file:
json.dump(tasks, file, indent=4)
# Function to display the menu
def show_menu():
print("\n--- To-Do List Menu ---")
print("1. View Tasks")
print("2. Add a Task")
print("3. Mark a Task as Completed")
print("4. Delete a Task")
print("5. Sort Tasks")
print("6. Search Tasks")
print("7. Send Reminders")
print("8. Exit")
# Function to view all tasks
def view_tasks():
if not tasks:
print("\nNo tasks available.")
else:
print("\n--- Your Tasks ---")
for index, task in enumerate(tasks, start=1):
status = "Done" if task["completed"] else "Not Done"
due_date = task.get("due_date", "No due date")
priority = task.get("priority", "No priority")
print(f"{index}. {task['name']} - Priority: {priority} - Due: {due_date} - {status}")
# Function to add a task
def add_task():
task_name = input("\nEnter the task name: ")
due_date = input("Enter the due date (YYYY-MM-DD, optional): ")
priority = input("Enter the priority (High/Medium/Low, optional): ")
# Validate due date format
if due_date:
try:
datetime.strptime(due_date, "%Y-%m-%d")
except ValueError:
print("Invalid date format. Please use YYYY-MM-DD.")
return
# Add task to the list
task = {
"name": task_name,
"completed": False,
"due_date": due_date if due_date else None,
"priority": priority if priority else None,
}
tasks.append(task)
save_tasks()
print(f"Task '{task_name}' added successfully!")
# Function to mark a task as completed
def mark_completed():
view_tasks()
try:
task_number = int(input("\nEnter the task number to mark as completed: "))
if 1 <= task_number <= len(tasks):
tasks[task_number - 1]["completed"] = True
save_tasks()
print(f"Task '{tasks[task_number - 1]['name']}' marked as completed!")
else:
print("Invalid task number.")
except ValueError:
print("Please enter a valid number.")
# Function to delete a task
def delete_task():
view_tasks()
try:
task_number = int(input("\nEnter the task number to delete: "))
if 1 <= task_number <= len(tasks):
deleted_task = tasks.pop(task_number - 1)
save_tasks()
print(f"Task '{deleted_task['name']}' deleted successfully!")
else:
print("Invalid task number.")
except ValueError:
print("Please enter a valid number.")
# Function to sort tasks by due date or priority
def sort_tasks():
print("\n--- Sort Tasks ---")
print("1. Sort by Due Date")
print("2. Sort by Priority")
choice = input("Enter your choice (1-2): ")
if choice == "1":
tasks.sort(key=lambda x: x.get("due_date", "9999-12-31")) # Default to far future if no due date
print("Tasks sorted by due date.")
elif choice == "2":
priority_order = {"High": 1, "Medium": 2, "Low": 3}
tasks.sort(key=lambda x: priority_order.get(x.get("priority", "Low"), 4))
print("Tasks sorted by priority.")
else:
print("Invalid choice.")
save_tasks()
# Function to search tasks by name
def search_tasks():
search_term = input("\nEnter a search term: ")
found_tasks = [task for task in tasks if search_term.lower() in task["name"].lower()]
if found_tasks:
print("\n--- Search Results ---")
for index, task in enumerate(found_tasks, start=1):
status = "Done" if task["completed"] else "Not Done"
due_date = task.get("due_date", "No due date")
priority = task.get("priority", "No priority")
print(f"{index}. {task['name']} - Priority: {priority} - Due: {due_date} - {status}")
else:
print("No tasks found matching your search.")
# Function to send reminders for tasks due soon
def send_reminders():
today = datetime.now()
due_soon_tasks = [task for task in tasks if task.get("due_date") and not task["completed"]]
due_soon_tasks = [
task for task in due_soon_tasks
if (datetime.strptime(task["due_date"], "%Y-%m-%d") - today) <= timedelta(days=1)
]
if due_soon_tasks:
print("\n--- Reminders ---")
for task in due_soon_tasks:
print(f"Task '{task['name']}' is due on {task['due_date']}!")
else:
print("\nNo tasks due soon.")
# Main function to run the application
def main():
global tasks
tasks = load_tasks()
while True:
show_menu()
choice = input("\nEnter your choice (1-8): ")
if choice == "1":
view_tasks()
elif choice == "2":
add_task()
elif choice == "3":
mark_completed()
elif choice == "4":
delete_task()
elif choice == "5":
sort_tasks()
elif choice == "6":
search_tasks()
elif choice == "7":
send_reminders()
elif choice == "8":
print("\nExiting the application. Goodbye!")
break
else:
print("\nInvalid choice. Please try again.")
# Run the application
if __name__ == "__main__":
main()
Python Code
--- To-Do List Menu ---
1. View Tasks
2. Add a Task
3. Mark a Task as Completed
4. Delete a Task
5. Sort Tasks
6. Search Tasks
7. Send Reminders
8. Exit
Adding a Task:
Python Code
Enter the task name: Finish Python Project
Enter the due date (YYYY-MM-DD, optional): 2023-10-15
Enter the priority (High/Medium/Low, optional): High
Task 'Finish Python Project' added successfully!