Add up disk usage across servers
easyLoops
Problem statement
A common thing to do with a list of numbers is add them all up, total disk usage across every server, total memory across a fleet, total requests across endpoints. The pattern is always the same: start a running total at 0 before the loop, then add each value to it as the loop visits it.
Common mistake: resetting the total inside the loop instead of before it.
TEXT
Wrong:for usage in disk_usages: total = 0 total += usagePutting total = 0 inside the loop wipes it out on every single pass, so at the end total only ever holds the last value added, not the sum of all of them. The reset has to happen once, before the loop starts.
Your task: given disk usage per server, [45.5, 60.2, 30.0], print the total.
Expected output:
TEXT
135.7Approach
Set total to 0 once, then add each value to it as the loop goes:
disk_usages = [45.5, 60.2, 30.0]
total = 0
for usage in disk_usages:
total += usage
print(total)