Functions
Project: reusable study summary
Split a study summary into small functions that return useful values.
Lesson 28 of 63
Reading: about 2 min
Lesson + practice: about 16 min
Difficulty: Beginner
On this page4 sections
Create study_summary.py. Reuse what you know about lists and dictionaries, but place calculations and formatting in named functions.
Build the summary
def total_minutes(sessions: list[dict[str, int]]) -> int:
"""Add the minutes from all study sessions."""
total = 0
for session in sessions:
total += session["minutes"]
return total
def format_duration(minutes: int) -> str:
"""Format minutes as hours and remaining minutes."""
return f"{minutes // 60} h {minutes % 60} min"
sessions = [{"minutes": 25}, {"minutes": 40}, {"minutes": 30}]
print(f"Study time: {format_duration(total_minutes(sessions))}")Study time: 1 h 35 min
Why this works
total_minutes() handles the data calculation and returns one integer. format_duration() handles presentation and returns a string. The final print combines them. Separating calculation from display makes each function easier to inspect and reuse with a different output format.
Check and extend
Run the program, then add a 25-minute session. Predict 2 h 0 min before rerunning. Explain which function performs arithmetic and which formats the message.
Why do both functions return a value?
Reveal answer
Returning lets the caller combine their results into the final message.
Try another case
If the sessions total 125 minutes, what does format_duration() return?
Check your answer
Reveal answer
It returns the string "2 h 5 min".
Your progress
Reveal the check answer or reach the end to complete this lesson.