DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Day 15: Uncovering Spending Habits with Semester Averages

Welcome to Day 15 of the #80DaysOfChallenges journey! Today’s challenge took me into practical territory: calculating average expenses for each semester from a list of monthly spending data. This intermediate-level task was a solid chance to work with for loops, enumerate(), tuple unpacking, and straightforward arithmetic in Python. It felt like a real-world budgeting exercise, showing how even everyday data can sharpen your skills in iteration and data organization.


💡 Key Takeaways from Day 15: Semester Expenses Calculator

This challenge uses a list of 12 monthly expenses to compute averages for two semesters: January–June and July-December. The formula is basic, sum the relevant months and divide by six, but the focus is on efficient looping, smart indexing, and clean data return. Let’s unpack the essentials: iterating with loops, indexing via enumerate(), and tuple unpacking for results.

1. The Loop: Accumulating Totals the Reliable Way

At its core, the task is about summing expenses into two buckets based on month position. A simple for loop does the heavy lifting, iterating over the list and adding values conditionally. The calculate_semester_averages function starts by initializing totals:

first_semester_total = 0
second_semester_total = 0

for index, expense in enumerate(expenses):
    if index < 6:   # First six months (Jan–Jun) belong to the first semester
        first_semester_total += expense  # Sum expenses for Jan–Jun
    else:
        second_semester_total += expense  # Sum expenses for Jul–Dec
Enter fullscreen mode Exit fullscreen mode

I appreciated how unpretentious this is, no fancy reductions, just a straightforward accumulation. It mirrors how you'd tally receipts in a spreadsheet: go through each item, decide where it fits, and add it up. Running it on the sample data (like $2950.75 for January) quickly builds totals of around $17,544 for the first semester and $18,775 for the second. It's a quiet reminder that loops are the backbone of processing sequences, especially when the logic is this linear.

2. Enumerate: Getting Index and Value Without the Hassle

One of the nicer touches here is using enumerate() inside the loop, which pairs each expense with its zero-based index. This avoids the old-school counter variable (i = 0; i += 1), making the code cleaner and less error-prone:

for index, expense in enumerate(expenses):
    if index < 6:
        # ...
Enter fullscreen mode Exit fullscreen mode

What clicked for me was how enumerate turns a simple list traversal into something more intentional. Without it, I'd have to track the index manually, which invites off-by-one bugs. Here, it naturally splits the year at index 6, handling the semester divide without extra math. It's one of those Python idioms that feels small but saves mental overhead, I've already caught myself reaching for it in unrelated scripts this week.

3. Tuple Unpacking: Returning and Using Data Neatly

Once the averages are calculated (total / 6), the function packs them into a tuple for return:

first_avg = first_semester_total / 6
second_avg = second_semester_total / 6
return first_avg, second_avg  # Return averages as a tuple
Enter fullscreen mode Exit fullscreen mode

Then, unpacking makes calling it a breeze:

first_avg, second_avg = calculate_semester_averages(monthly_spending)

print(f"\nAverage expenses for the first semester:  ${first_avg:.2f}")
print(f"Average expenses for the second semester: ${second_avg:.2f}\n")
Enter fullscreen mode Exit fullscreen mode

This outputs something like $2924.07 and $3129.27, formatted to two decimals for that clean financial look. I like how unpacking keeps the main script readable, it's symmetric and explicit, assigning both values in one line. It also hints at scalability; if I added a third metric (say, yearly total), the tuple could grow without rewriting the caller. Small win, but it makes the whole thing feel polished.


🎯 Summary and Reflections

This challenge highlighted how Python turns mundane data tasks into elegant flows. It pushed me to consider:

  • Iteration efficiency: Loops for summing lists, with conditions keeping things targeted.
  • Built-in helpers: enumerate() for free indexing, reducing boilerplate.
  • Data flow: Tuples and unpacking for concise returns that play nice with the rest of your code.

The unexpected part? How therapeutic it felt to simulate budgeting. Staring at those expense numbers made me audit my own coffee habit, coding as accidental self-reflection. For extensions, I could slice the list directly (sum(expenses[:6]) / 6) for brevity, or pull in pandas to handle real CSV budgets with trends over years.


🚀 Next Steps and Resources

Day 15 grounded me in list handling and practical math, prepping for data-heavy challenges down the line. If you're in the #80DaysOfChallenges groove, what tweaks did you make to this one? Any loop hacks or unpacking tips? Let's hear it!

Top comments (0)