Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKayc M
12,593 PointsWhat if I wanted to sum it all together after iterating them?
How do I automate the script to give me a final value of 147.25
2 Answers
Mustafa Başaran
28,046 PointsHi Kayc,
You may need a for loop within a for loop for this. Please follow the steps below.
# declare a total_sum variable and set it equal to zero
total_sum = 0
# iterate over travel_expenses list. On each iteration, t_e is a sublist within travel_expenses, right?
for t_e in travel_expenses:
# now, iterate over t_e. This will give you each and every element within a sublist on that iteration.
for i in t_e:
# add each element, i, to total_sum.
total_sum += i
# then, you will have every element summed up.
#Yes, it is 147.25.
print(total_sum)
I hope this helps.
Robert Aguirre
14,617 Pointstravel_expenses = [
[5.00, 2.75, 22.00, 0.00, 0.00],
[24.75, 5.50, 15.00, 22.00, 8.00],
[2.75, 5.50, 0.00, 29.00, 5.00],
]
print("Travel Expenses:")
week_number = 1
running_total = 0
for week in travel_expenses:
weekly_sum = sum(week)
running_total += weekly_sum
print("* Week #{}: ${}".format(week_number, weekly_sum))
week_number += 1
print("Your current total expenses are {}".format(running_total))
Kayc M
12,593 PointsKayc M
12,593 PointsI looked it up on Google for a while and nothing. That's exactly what I was looking for, thank you.
Cao Tru
Courses Plus Student 1,103 PointsCao Tru
Courses Plus Student 1,103 PointsMake sense. Thanks