Build mission control.
Combine your new skills into a tiny task-reporting tool.
01 The idea
A useful program is often a few simple ideas working together. This mini build combines dictionaries for records, a list for a collection, a comprehension for filtering, and a function that returns a summary. Start with working data, then add one capability at a time.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def mission_report(tasks):
open_tasks = [task for task in tasks if not task["done"]]
minutes = sum(task["minutes"] for task in open_tasks)
return f"{len(open_tasks)} open tasks / {minutes} minutes"
tasks = [
{"name": "Sketch", "done": True, "minutes": 15},
{"name": "Build", "done": False, "minutes": 40},
{"name": "Test", "done": False, "minutes": 20},
]
print(mission_report(tasks))2 open tasks / 60 minutes
03 Under the hood
- 1
Each task record uses the same keys. Consistent data shapes make the rest of the program easier to reason about.
- 2
The comprehension keeps unfinished tasks. The generator expression feeds their estimated minutes to sum().
- 3
mission_report() returns text instead of printing internally. That makes its result easy to display, test, or write to a file. Next, consider loading the tasks from JSON and validating that minutes is nonnegative.
04 Your turn, builder
Write a completed_names(tasks) function that returns the names of completed tasks. Try it with an empty list too.
Reveal one possible solution +
def completed_names(tasks):
return [task["name"] for task in tasks if task["done"]]
print(completed_names([{"name": "Sketch", "done": True}]))
print(completed_names([]))05 Check your signal
Why return a report string instead of printing inside the function?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.