
Hey techie! In my last post, I gave you a mini project on match-case with a touch of OOP (Build a Task Manager with Python’s match-case).
Did you nail it? Well, congratulations if you did! But if you found it super challenging, fret not—I’ve got your back.
I’ve done the hard work for you. All you need to do now is sit back, grab a cup of coffee, and unwrap this little twist of code fun.
I’m not going to waste your precious time with theories—we’ve done all the good talk in the main tutorial. You can go back there and do a quick recap if you need to. So let’s get down to business at once!
Project: Command-Line Task Manager
The code below is a complete task manager solution that uses match-case for command parsing:
from datetime import datetime
class Task:
def __init__(self, task_id, name, priority):
self.id = task_id
self.name = name
self.priority = priority
self.status = "pending"
self.created_at = datetime.now()
def complete(self):
self.status = "completed"
def __repr__(self):
timestamp = self.created_at.strftime("%Y-%m-%d %H:%M")
return f"[{self.id}] {self.name} | Priority: {self.priority} | Status: {self.status} | Created: {timestamp}"
class TaskManager:
def __init__(self):
self.tasks = []
self.next_id = 1
def parse_command(self, command):
parts = command.split()
match parts:
case ["help"]:
return self.show_help()
case ["add", *task_parts] if len(task_parts) >= 2:
priority = task_parts[-1].lower()
name = " ".join(task_parts[:-1])
return self.add_task(name, priority)
case ["list"]:
return self.list_tasks()
case ["list", filter_by]:
return self.list_tasks(filter_by.lower())
case ["complete", task_id]:
try:
return self.complete_task(int(task_id))
except ValueError:
return "❌ Invalid task ID. Must be a number."
case ["delete", task_id]:
try:
return self.delete_task(int(task_id))
except ValueError:
return "❌ Invalid task ID. Must be a number."
case ["stats"]:
return self.show_stats()
case ["search", *keywords]:
keyword = " ".join(keywords)
return self.search_tasks(keyword)
case ["exit"] | ["quit"]:
print("👋 Thanks for using Task Manager. Goodbye!")
exit()
case _:
return "❌ Unknown command. Type 'help' for available commands."
def add_task(self, name, priority):
match priority:
case "low" | "medium" | "high":
task = Task(self.next_id, name, priority)
self.tasks.append(task)
self.next_id += 1
return f"✅ Task added: {task}"
case _:
return "❌ Invalid priority. Use: low, medium, or high"
def list_tasks(self, filter_by="all"):
if not self.tasks:
return "📭 No tasks found. Add some tasks to get started!"
match filter_by:
case "all":
filtered = self.tasks
title = "All Tasks"
case "completed":
filtered = [t for t in self.tasks if t.status == "completed"]
title = "Completed Tasks"
case "pending":
filtered = [t for t in self.tasks if t.status == "pending"]
title = "Pending Tasks"
case "high" | "medium" | "low":
filtered = [t for t in self.tasks if t.priority == filter_by]
title = f"{filter_by.capitalize()} Priority Tasks"
case _:
return "❌ Invalid filter. Use: all, completed, pending, high, medium, or low"
if not filtered:
return f"📭 No tasks found for filter: {filter_by}"
result = [f"\n{'='*60}", f" {title} ({len(filtered)} tasks)", f"{'='*60}"]
for task in filtered:
result.append(f" {task}")
result.append(f"{'='*60}")
return "\n".join(result)
def complete_task(self, task_id):
for task in self.tasks:
if task.id == task_id:
if task.status == "completed":
return f"ℹ️ Task {task_id} is already completed"
task.complete()
return f"✅ Task {task_id} marked as completed: {task.name}"
return f"❌ Task {task_id} not found"
def delete_task(self, task_id):
for i, task in enumerate(self.tasks):
if task.id == task_id:
deleted_task = self.tasks.pop(i)
return f"🗑️ Task deleted: {deleted_task.name}"
return f"❌ Task {task_id} not found"
def show_stats(self):
if not self.tasks:
return "📊 No statistics available. Add some tasks first!"
total = len(self.tasks)
completed = len([t for t in self.tasks if t.status == "completed"])
pending = total - completed
high = len([t for t in self.tasks if t.priority == "high"])
medium = len([t for t in self.tasks if t.priority == "medium"])
low = len([t for t in self.tasks if t.priority == "low"])
stats = [
"\n" + "="*40,
" 📊 Task Statistics",
"="*40,
f" Total Tasks: {total}",
f" Completed: {completed} ({completed/total*100:.1f}%)",
f" Pending: {pending} ({pending/total*100:.1f}%)",
"",
" By Priority:",
f" 🔴 High: {high}",
f" 🟡 Medium: {medium}",
f" 🟢 Low: {low}",
"="*40
]
return "\n".join(stats)
def search_tasks(self, keyword):
if not self.tasks:
return "📭 No tasks to search"
results = [t for t in self.tasks if keyword.lower() in t.name.lower()]
if not results:
return f"❌ No tasks found matching '{keyword}'"
result = [f"\n🔍 Search results for '{keyword}' ({len(results)} found):"]
for task in results:
result.append(f" {task}")
return "\n".join(result)
def show_help(self):
help_text = """
╔════════════════════════════════════════════════════════════╗
║ TASK MANAGER - COMMAND REFERENCE ║
╚════════════════════════════════════════════════════════════╝
📝 ADD TASK:
add [task_name] [priority]
Example: add "Buy groceries" high
📋 LIST TASKS:
list [filter]
Filters: all, completed, pending, high, medium, low
Example: list pending
✅ COMPLETE TASK:
complete [task_id]
Example: complete 1
🗑️ DELETE TASK:
delete [task_id]
Example: delete 2
🔍 SEARCH TASKS:
search [keyword]
Example: search grocery
📊 VIEW STATISTICS:
stats
❓ SHOW HELP:
help
🚪 EXIT PROGRAM:
exit or quit
═══════════════════════════════════════════════════════════════
"""
return help_text
def run(self):
print("""
╔════════════════════════════════════════════════════════════╗
║ 🎯 WELCOME TO PYTHON TASK MANAGER 🎯 ║
║ ║
║ Your productivity companion for getting ║
║ things done, the Python way! ║
╚════════════════════════════════════════════════════════════╝
""")
print("Type 'help' to see available commands.\n")
while True:
try:
command = input("📌 > ").strip()
if command:
result = self.parse_command(command)
print(result)
except KeyboardInterrupt:
print("\n\n👋 Goodbye! Come back when you have more tasks!")
break
except Exception as e:
print(f"❌ Error: {e}")
if __name__ == "__main__":
manager = TaskManager()
manager.run()
Hmm… I hope that was fun! 🎉
Now, I know you might have some questions depending on your experience level in programming. Well, the comment box is wide open—use it! Your mysteries will turn into lessons.
Pro tip though: You can easily copy this code into your VSCode and let GitHub Copilot help you explore it further. Let me know if you need a guide on how to use Copilot in VSCode; I want you to learn how to learn on your own too! 💡
How the Solution Uses Match-Case:
- Command Parsing – Main
parse_command()uses match-case to route commands - Priority Validation –
add_task()validates priorities with match-case - Task Filtering –
list_tasks()filters using match-case patterns - Pattern Matching – Uses
*to capture variable-length arguments - Guards – Uses
ifclauses for additional validation
Testing the Application:
📌 > add "Learn Python match-case" high
✅ Task added: [1] Learn Python match-case | Priority: high | Status: pending
📌 > add "Practice coding" medium
✅ Task added: [2] Practice coding | Priority: medium | Status: pending
📌 > add "Read documentation" low
✅ Task added: [3] Read documentation | Priority: low | Status: pending
📌 > list all
============================================================
All Tasks (3 tasks)
============================================================
[1] Learn Python match-case | Priority: high | Status: pending
[2] Practice coding | Priority: medium | Status: pending
[3] Read documentation | Priority: low | Status: pending
============================================================
📌 > complete 1
✅ Task 1 marked as completed: Learn Python match-case
📌 > stats
========================================
📊 Task Statistics
========================================
Total Tasks: 3
Completed: 1 (33.3%)
Pending: 2 (66.7%)
By Priority:
🔴 High: 1
🟡 Medium: 1
🟢 Low: 1
========================================
What’s Next? Keep Practicing
The best way to master match-case is to use it in your own projects. Here are some ideas:
- Refactor your old code – Find if-elif chains in your existing projects and convert them to match-case
- Build a game – Create a text-based adventure game or a simple RPG where match-case handles player actions
- Create a CLI tool – Build command-line utilities that parse user commands
- Data processing – Use pattern matching to handle different data structures in your data analysis projects
Resources:
REMEMBER! If you need personalized training in Python programming or any other course listed on our website, you can always always get started with just a click.
Talk soon! 🚀
