Congratulations! You've learned the fundamentals of Python programming. You understand variables, data types, conditionals, loops, lists, dictionaries, functions, string manipulation, error handling, and file operations. Now it's time to put it all together and build something real.
In this final lesson, we'll create a complete Task Manager application that uses every concept you've learned. This project will demonstrate how all these pieces fit together to create a functional, useful program. By building this application, you'll see how professional programs are structured and gain confidence in your Python skills.
What You'll Learn
- How to structure a complete Python application
- Combining all concepts into a working program
- Organizing code with functions
- Creating a user-friendly interface
- Persisting data with files
- Handling errors gracefully
- Best practices for program organization
- Planning and building a project from scratch
Project Overview: Task Manager
We'll build a Task Manager that allows users to:
- Add new tasks
- View all tasks
- Mark tasks as complete
- Delete tasks
- Save tasks to a file
- Load tasks from a file
This project will use:
- Variables and data types (storing task information)
- Lists (storing multiple tasks)
- Dictionaries (organizing task data)
- Functions (organizing code)
- Loops (processing tasks, menu system)
- Conditionals (making decisions)
- File handling (saving/loading tasks)
- Error handling (graceful error management)
- String manipulation (formatting output)
Step 1: Planning the Structure
Before writing code, let's plan our application structure:
# Task Manager Structure
# - Tasks will be stored as dictionaries in a list
# - Each task has: title, description, completed status
# - Functions for: add, view, complete, delete, save, load
# - Main menu loop for user interaction
# - File storage for persistence
Step 2: Core Data Structure
Let's start by defining how we'll store tasks:
# Task structure
# Each task is a dictionary:
task = {
"title": "Learn Python",
"description": "Complete Python for Beginners course",
"completed": False
}
# All tasks stored in a list
tasks = [task1, task2, task3]
Step 3: Building the Complete Application
Here's the complete Task Manager application:
# task_manager.py - Complete Task Manager Application
import json
from datetime import datetime
# File to store tasks
TASKS_FILE = "tasks.json"
def load_tasks():
"""Load tasks from file."""
try:
with open(TASKS_FILE, "r") as file:
tasks = json.load(file)
return tasks
except FileNotFoundError:
return []
except json.JSONDecodeError:
print("Error: Corrupted tasks file. Starting fresh.")
return []
def save_tasks(tasks):
"""Save tasks to file."""
try:
with open(TASKS_FILE, "w") as file:
json.dump(tasks, file, indent=2)
return True
except Exception as e:
print(f"Error saving tasks: {e}")
return False
def add_task(tasks):
"""Add a new task."""
print("\n--- Add New Task ---")
title = input("Enter task title: ").strip()
if not title:
print("Error: Task title cannot be empty!")
return tasks
description = input("Enter task description (optional): ").strip()
new_task = {
"title": title,
"description": description if description else "No description",
"completed": False,
"created": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
tasks.append(new_task)
print(f"Task '{title}' added successfully!")
return tasks
def view_tasks(tasks):
"""Display all tasks."""
print("\n--- Your Tasks ---")
if not tasks:
print("No tasks found. Add some tasks to get started!")
return
for index, task in enumerate(tasks, 1):
status = "✓" if task["completed"] else " "
print(f"\n{index}. [{status}] {task['title']}")
print(f" Description: {task['description']}")
print(f" Created: {task.get('created', 'Unknown')}")
# Show summary
completed = sum(1 for task in tasks if task["completed"])
total = len(tasks)
print(f"\n--- Summary: {completed}/{total} tasks completed ---")
def complete_task(tasks):
"""Mark a task as complete."""
if not tasks:
print("No tasks to complete!")
return tasks
view_tasks(tasks)
try:
task_num = int(input("\nEnter task number to mark as complete: "))
if 1 <= task_num <= len(tasks):
task = tasks[task_num - 1]
if task["completed"]:
print(f"Task '{task['title']}' is already completed!")
else:
task["completed"] = True
print(f"Task '{task['title']}' marked as complete!")
else:
print("Invalid task number!")
except ValueError:
print("Please enter a valid number!")
return tasks
def delete_task(tasks):
"""Delete a task."""
if not tasks:
print("No tasks to delete!")
return tasks
view_tasks(tasks)
try:
task_num = int(input("\nEnter task number to delete: "))
if 1 <= task_num <= len(tasks):
deleted_task = tasks.pop(task_num - 1)
print(f"Task '{deleted_task['title']}' deleted successfully!")
else:
print("Invalid task number!")
except ValueError:
print("Please enter a valid number!")
return tasks
def show_menu():
"""Display the main menu."""
print("\n" + "=" * 40)
print(" TASK MANAGER")
print("=" * 40)
print("1. Add Task")
print("2. View Tasks")
print("3. Complete Task")
print("4. Delete Task")
print("5. Save and Exit")
print("=" * 40)
def main():
"""Main program loop."""
print("Welcome to Task Manager!")
# Load existing tasks
tasks = load_tasks()
if tasks:
print(f"Loaded {len(tasks)} task(s) from file.")
# Main menu loop
while True:
show_menu()
choice = input("Enter your choice (1-5): ").strip()
if choice == "1":
tasks = add_task(tasks)
elif choice == "2":
view_tasks(tasks)
elif choice == "3":
tasks = complete_task(tasks)
elif choice == "4":
tasks = delete_task(tasks)
elif choice == "5":
if save_tasks(tasks):
print(f"\nTasks saved successfully! Goodbye!")
else:
print("\nWarning: Could not save tasks!")
break
else:
print("Invalid choice! Please enter 1-5.")
# Auto-save after each operation
save_tasks(tasks)
# Run the program
if __name__ == "__main__":
main()
Understanding the Code
Let's break down how this application uses everything you've learned:
Variables and Data Types:
- Tasks stored as dictionaries with string and boolean values
- Lists to store multiple tasks
- Variables for user input and choices
Functions:
- Each major operation is a separate function
- Functions return modified data
- Clear separation of concerns
Loops:
- Main menu loop (
while True) for continuous operation forloops to iterate through tasks
Conditionals:
if-elif-elsefor menu choices- Validation of user input
- Checking task status
Error Handling:
- Try-except blocks for file operations
- Input validation
- Graceful error messages
File Handling:
- Loading tasks from JSON file
- Saving tasks to JSON file
- Handling file not found errors
String Manipulation:
- Formatting output
- Stripping whitespace from input
- Creating formatted displays
Running the Application
To use the Task Manager:
- Save the code to a file named
task_manager.py - Run it:
python task_manager.py - Use the menu to manage your tasks
- Tasks are automatically saved to
tasks.json
Enhancing the Application
Here are some ideas to extend this application:
# Enhancement ideas:
# 1. Add due dates
def add_due_date(task):
due_date = input("Enter due date (YYYY-MM-DD): ")
task["due_date"] = due_date
return task
# 2. Filter tasks
def view_incomplete_tasks(tasks):
incomplete = [task for task in tasks if not task["completed"]]
view_tasks(incomplete)
# 3. Search tasks
def search_tasks(tasks, keyword):
results = [task for task in tasks if keyword.lower() in task["title"].lower()]
return results
# 4. Sort tasks
def sort_tasks_by_date(tasks):
return sorted(tasks, key=lambda x: x.get("created", ""), reverse=True)
Key Takeaways
This project demonstrates:
- Organization: Code is organized into logical functions
- Reusability: Functions can be called multiple times
- Error Handling: Program handles errors gracefully
- User Experience: Clear menus and helpful messages
- Data Persistence: Tasks are saved between sessions
- Modularity: Each feature is a separate function
Try It Yourself
Now that you've seen a complete application, try these challenges:
-
Add Features: Implement due dates, priorities, or categories for tasks
-
Improve UI: Add colors, better formatting, or ASCII art to the menu
-
Add Validation: Ensure task titles are unique or validate date formats
-
Create Your Own Project: Build something you're interested in:
a. Personal budget tracker
b. Recipe manager
c. Book collection tracker
d. Habit tracker -
Refactor: Improve the code by adding more functions or better organization
Summary
Congratulations! You've completed the Python for Beginners course and built a complete application. Throughout these 12 lessons, you've learned:
- Python fundamentals (variables, data types, operators)
- Control flow (conditionals, loops)
- Data structures (lists, dictionaries)
- Functions for code organization
- String manipulation techniques
- Error handling for robust programs
- File operations for data persistence
- How to combine everything into real applications
You now have a solid foundation in Python programming. The concepts you've learned apply to any programming language and will serve you well as you continue your programming journey.
Remember: programming is a skill that improves with practice. Keep building projects, solving problems, and exploring Python's vast ecosystem. The Python community is welcoming and helpful, and there are countless resources available as you continue learning.
What's Next?
You've completed the Python for Beginners course! Here are some suggestions for continuing your Python journey:
- Practice: Build more projects to reinforce what you've learned
- Explore Libraries: Learn about popular Python libraries (requests, pandas, etc.)
- Advanced Topics: Study object-oriented programming, modules, and packages
- Specialize: Choose an area that interests you (web development, data science, automation)
- Join Communities: Connect with other Python learners and developers
- Build a Portfolio: Create projects that showcase your skills
Keep coding, keep learning, and most importantly, have fun! Python is a powerful tool, and you now have the foundation to build amazing things with it.