1. Introduction
Learning Python becomes more meaningful when you start building applications that solve everyday problems. In this capstone project, we will create an Interactive Task Organizer using Python.
Imagine that you have several activities to complete every day. You need a simple application where you can record your tasks, check what is pending, mark completed activities, and remove tasks that are no longer required.
We will build exactly that application using Python's built-in features. No external libraries or database are required for this first version.
- Add a new task with a title and description.
- Display all tasks with their current status.
- Mark a task as completed.
- Delete a task using its ID.
- View pending and completed task summaries.
- Handle invalid menu choices and user input.
2. Project Requirements
Before writing code, let's define what our application should do.
| Feature | Description |
|---|---|
| Add Task | Accept a task title and description from the user. |
| View Tasks | Display all saved tasks with their IDs and statuses. |
| Complete Task | Change a task's status from pending to completed. |
| Delete Task | Remove a task using its unique ID. |
| Task Summary | Display total, pending, and completed task counts. |
| Exit | Close the application safely. |
3. Concepts Used in This Project
This project combines several Python concepts that you have already learned.
| Python Concept | How We Use It |
|---|---|
| Variables | Store task IDs, titles, descriptions, and counts. |
| Lists | Maintain multiple tasks in memory. |
| Dictionaries | Represent individual tasks using key-value pairs. |
| Functions | Separate application features into reusable blocks. |
| Conditional Statements | Process the user's selected menu option. |
| Loops | Keep the application running until the user exits. |
| For Loop | Display and search through tasks. |
| Input Validation | Prevent empty titles and invalid task IDs. |
4. Understanding the Application Workflow
The application starts by displaying a menu. The user selects an operation, and Python calls the corresponding function. After completing the operation, the application displays the menu again.
5. Designing the Task Data Structure
We need a way to store multiple tasks. A Python list is suitable for holding all tasks, while a dictionary can represent each individual task.
For example, one task can look like this:
task = {
"id": 1,
"title": "Learn Python",
"description": "Complete Python practice exercises",
"completed": False
}
Here is what each field represents:
- id – A unique number used to identify the task.
- title – The name of the task.
- description – Additional information about the task.
- completed – A Boolean value indicating whether the task is complete.
We will store these dictionaries inside a list named tasks.
6. Complete Python Project
Now let's implement the complete application. Create a Python file named task_organizer.py and add the following code.
tasks = []
next_task_id = 1
def add_task():
global next_task_id
print("\n--- Add New Task ---")
title = input("Enter task title: ").strip()
if not title:
print("Task title cannot be empty.")
return
description = input("Enter task description: ").strip()
task = {
"id": next_task_id,
"title": title,
"description": description,
"completed": False
}
tasks.append(task)
next_task_id += 1
print("Task added successfully!")
def view_tasks():
print("\n--- All Tasks ---")
if not tasks:
print("No tasks available.")
return
for task in tasks:
status = "Completed" if task["completed"] else "Pending"
print(f"\nTask ID: {task['id']}")
print(f"Title: {task['title']}")
print(f"Description: {task['description']}")
print(f"Status: {status}")
def complete_task():
print("\n--- Complete Task ---")
if not tasks:
print("No tasks available to complete.")
return
try:
task_id = int(input("Enter task ID: "))
for task in tasks:
if task["id"] == task_id:
if task["completed"]:
print("This task is already completed.")
else:
task["completed"] = True
print("Task marked as completed!")
return
print("Task ID not found.")
except ValueError:
print("Please enter a valid numeric task ID.")
def delete_task():
print("\n--- Delete Task ---")
if not tasks:
print("No tasks available to delete.")
return
try:
task_id = int(input("Enter task ID: "))
for index, task in enumerate(tasks):
if task["id"] == task_id:
deleted_task = tasks.pop(index)
print(f"Task '{deleted_task['title']}' deleted.")
return
print("Task ID not found.")
except ValueError:
print("Please enter a valid numeric task ID.")
def show_summary():
total_tasks = len(tasks)
completed_tasks = sum(
1 for task in tasks if task["completed"]
)
pending_tasks = total_tasks - completed_tasks
print("\n--- Task Summary ---")
print(f"Total Tasks: {total_tasks}")
print(f"Completed Tasks: {completed_tasks}")
print(f"Pending Tasks: {pending_tasks}")
def display_menu():
print("\n========== TASK ORGANIZER ==========")
print("1. Add Task")
print("2. View All Tasks")
print("3. Complete Task")
print("4. Delete Task")
print("5. View Task Summary")
print("6. Exit")
print("====================================")
def main():
print("Welcome to Interactive Task Organizer!")
while True:
display_menu()
choice = input("Select an option (1-6): ").strip()
if choice == "1":
add_task()
elif choice == "2":
view_tasks()
elif choice == "3":
complete_task()
elif choice == "4":
delete_task()
elif choice == "5":
show_summary()
elif choice == "6":
print("\nThank you for using Task Organizer!")
break
else:
print("Invalid choice. Please select an option from 1 to 6.")
if __name__ == "__main__":
main()
7. Understanding the Important Functions
7.1 Adding a Task
The add_task() function accepts user input, validates the title, creates a dictionary, and appends it to the tasks list.
task = {
"id": next_task_id,
"title": title,
"description": description,
"completed": False
}
tasks.append(task)
The append() method adds the new task to the end of the list. We then increment the ID so the next task receives a different identifier.
7.2 Viewing All Tasks
We use a for loop to iterate through the task list and display each task.
for task in tasks:
status = "Completed" if task["completed"] else "Pending"
print(task["id"], task["title"], status)
The conditional expression checks the Boolean value and displays the corresponding status.
7.3 Completing a Task
We search for the requested task ID. If the ID matches, we update the dictionary's completed value.
if task["id"] == task_id:
task["completed"] = True
This demonstrates how dictionaries can be updated after they have been added to a list.
7.4 Deleting a Task
We use enumerate() to access both the index and task while iterating through the list. When the task ID matches, pop() removes that task.
for index, task in enumerate(tasks):
if task["id"] == task_id:
tasks.pop(index)
break
7.5 Displaying the Task Summary
The summary calculates the total number of tasks and counts the completed tasks. Pending tasks are calculated by subtracting completed tasks from the total.
total_tasks = len(tasks)
completed_tasks = sum(
1 for task in tasks if task["completed"]
)
pending_tasks = total_tasks - completed_tasks
The sum() function counts the number of tasks for which the condition is true.
8. Running the Application
Open a terminal in the directory containing task_organizer.py and execute:
python task_organizer.py
Depending on your Python installation, you may need to use:
python3 task_organizer.py
9. Sample Application Output
Let's walk through a sample session where a user adds two tasks, completes one task, and checks the summary.
Welcome to Interactive Task Organizer! ========== TASK ORGANIZER ========== 1. Add Task 2. View All Tasks 3. Complete Task 4. Delete Task 5. View Task Summary 6. Exit ==================================== Select an option (1-6):
Select an option (1-6): 1 --- Add New Task --- Enter task title: Learn Python Enter task description: Complete Python practice exercises Task added successfully!
Select an option (1-6): 1 --- Add New Task --- Enter task title: Build Portfolio Enter task description: Create a personal developer portfolio Task added successfully!
Select an option (1-6): 2 --- All Tasks --- Task ID: 1 Title: Learn Python Description: Complete Python practice exercises Status: Pending Task ID: 2 Title: Build Portfolio Description: Create a personal developer portfolio Status: Pending
Select an option (1-6): 3 --- Complete Task --- Enter task ID: 1 Task marked as completed!
Select an option (1-6): 5 --- Task Summary --- Total Tasks: 2 Completed Tasks: 1 Pending Tasks: 1
10. How the Application Uses Python Control Flow
This project brings together the control-flow concepts used throughout the Python learning series.
| Code Element | Purpose |
|---|---|
| while True | Repeats the main menu until the user exits. |
| if / elif / else | Routes the selected menu option to the correct function. |
| for | Iterates over tasks to display or locate them. |
| break | Exits the main loop when the user chooses Exit. |
| return | Ends a function after its operation is complete. |
| try / except | Handles invalid numeric input without crashing. |
11. Handling Common Errors
A good application should handle unexpected input gracefully. Consider these situations:
The application should not allow a task without a title. We use strip() to remove surrounding whitespace and validate the result.
title = input("Enter task title: ").strip()
if not title:
print("Task title cannot be empty.")
return
If the user enters text instead of a number, converting it with int() raises a ValueError. We handle that exception.
try:
task_id = int(input("Enter task ID: "))
except ValueError:
print("Please enter a valid numeric task ID.")
If no task matches the entered ID, the application displays a clear message instead of attempting to update or delete an unrelated task.
12. Improving the Project – Save Tasks to a File
Our first version stores tasks only in memory. A useful next step is to save tasks in a JSON file so that they remain available after the program closes.
Python provides the built-in json module for this purpose.
12.1 Add JSON Import and File Functions
import json
import os
FILE_NAME = "tasks.json"
def load_tasks():
if not os.path.exists(FILE_NAME):
return []
try:
with open(FILE_NAME, "r", encoding="utf-8") as file:
return json.load(file)
except (json.JSONDecodeError, OSError):
print("Unable to read saved tasks.")
return []
def save_tasks():
try:
with open(FILE_NAME, "w", encoding="utf-8") as file:
json.dump(tasks, file, indent=4)
except OSError:
print("Unable to save tasks.")
12.2 Integrate File Persistence
To use this improvement, make the following changes to the original program:
- Import json and os.
- Initialize the task list using tasks = load_tasks() instead of an empty list.
- After adding, completing, or deleting a task, call save_tasks().
- Calculate the next task ID using the largest existing ID plus one.
tasks = load_tasks()
next_task_id = max(
(task["id"] for task in tasks),
default=0
) + 1
13. Additional Challenges
Once the basic application works, try extending it with the following features. These challenges will help you practise problem-solving and application design.
Add a priority field with values such as High, Medium, and Low. Display priority when viewing tasks.
Allow users to enter a due date for each task and display overdue tasks.
Allow users to search for tasks by title or description.
Add options to display only pending tasks or only completed tasks.
Allow users to update a task's title and description using its ID.
Add categories such as Work, Personal, Learning, and Shopping.
14. Best Practices Followed
- Use functions: Each feature has its own function, making the code easier to maintain.
- Use meaningful names: Names such as complete_task and show_summary describe their purpose.
- Validate input: Check user input before processing it.
- Handle exceptions: Use try / except for operations that can fail.
- Avoid unnecessary duplication: Reuse functions instead of repeating the same logic.
- Keep responsibilities separate: Menu handling, task operations, and data storage should remain separate as the application grows.
15. Interview Questions Based on This Project
Q1. Why did we use a list of dictionaries instead of multiple separate lists?
Answer: A list of dictionaries keeps related task information together. Each task has its own ID, title, description, and status, making the data easier to manage.
Q2. What is the purpose of the global keyword?
Answer: The global keyword allows a function to modify a variable defined in the global scope. In this project, it is used to increment next_task_id inside add_task().
Q3. What is the difference between break and return?
Answer: break exits the nearest loop, whereas return exits the current function and optionally sends a value back to the caller.
Q4. Why do we use enumerate() while deleting a task?
Answer: It provides both the index and the item during iteration. We need the index to remove the correct element using pop().
Q5. Why is input validation important?
Answer: Input validation prevents invalid values from causing unexpected behavior. It helps the application respond safely to empty titles, incorrect IDs, and unsupported menu options.
Q6. How can we preserve tasks after the program exits?
Answer: We can use file storage such as JSON, CSV, or a database. The JSON extension in this article demonstrates one approach.
16. Key Takeaways
In this capstone project, we created a practical Python application using the fundamentals covered throughout the learning series.
- Built a menu-driven command-line application.
- Managed structured data using lists and dictionaries.
- Organized application logic using functions.
- Applied loops and conditional statements to control execution.
- Handled invalid user input with exception handling.
- Explored JSON file storage for persistent data.
The most important lesson is that individual Python concepts become much more powerful when combined to solve a real problem. Keep experimenting with the additional challenges and gradually turn this small application into a more complete task management system.
17. Practice Assignment
Try building your own improved version without copying the complete program. Your application should include the following requirements:
- Create a task with a title, description, and priority.
- Display all tasks in a readable format.
- Mark a task as completed using its ID.
- Delete a task using its ID.
- Search for a task using a keyword.
- Save and load tasks using a JSON file.
- Display a summary of pending and completed tasks.
Upgradix by Shrash Studio – Learn Technology. Build Your Future.