Ex 14: Task Completion Tracker
Problem
We’re building a simple task tracker for a to-do app. Whenever a user completes tasks, our app should mark them as done.
Rules
- Define a function
mark_completed_tasks(tasks: list[str]) -> list[str]. - Iterate through the list using a
forloop. - Update each task's format to:
"Completed: {task}". - Return a new list with the updated task strings.
Boilerplate
Copy below code and paste to our IDE for head start.
# Write our code inside this function
def mark_completed_tasks(tasks: list[str]) -> list[str]:
pass # remove this
# Call with test data
print(mark_completed_tasks(["Laundry", "Buy groceries", "Study Python"]))
Expected Output
['Completed: Laundry', 'Completed: Buy groceries', 'Completed: Study Python']
Solution
Only view the solution after trying our best.
Show solution
def mark_completed_tasks(tasks: list[str]) -> list[str]:
completed_tasks: list[str] = []
for task in tasks:
completed_tasks.append(f"Completed: {task}")
return completed_tasks
# Test call
print(mark_completed_tasks(["Laundry", "Buy groceries", "Study Python"]))
Details
A for loop is the most idiomatic way to process items in a list. Inside the loop, we use an f-string to format the new string and then append() it to our results list.