Modules and environments
Project: reusable study report
Extract a reusable calculation and run it from a separate script.
Lesson 43 of 63
Reading: about 1 min
Lesson + practice: about 19 min
Difficulty: Intermediate
On this page5 sections
Build study_report.py with a pure calculation function, then call it from a small driver. Save both files in the same practice folder and run python run_report.py.
Worked example
def total_minutes(sessions):
return sum(sessions)from study_report import total_minutes
print(f"Total: {total_minutes([20, 25, 30])} min")Total: 75 min
Why this works
The calculation is reusable because it takes data as an argument and returns a value. The driver owns printing. Running python run_report.py imports study_report.py from the same folder.
Another case
A second driver can reuse the same function without copying it.
from study_report import total_minutes
week = [30, 30, 45]
print(total_minutes(week) / len(week))35.0
Practice
Change the list in run_report.py to [15, 15], rerun python run_report.py, and predict its output.
Check the practice result
Reveal answer
It prints Total: 30 min.
Try another case
Why does total_minutes() return the sum instead of printing it?
Check your answer
Reveal answer
So any caller can use the number: print it, average it, or test it. The driver decides how to display the result.
Your progress
Reveal the check answer or reach the end to complete this lesson.