Change for to while loop - in Python Loops: Medical Insurance Estimates. vs. Costs Project

In the Python Loops: Medical Insurance Estimates vs. Costs Project the Extra project was to convert the first for loop to a while loop.

I tried several ways and the loop I have below seems to work. I don’t understand how it works though. My main point of confusion is how the i seems to be working for the index of the actual_insurance_costs. eg total_cost += actual_insurance_costs[i]

I created i as my counter variable, so how is it grabbing each value in the list? Is it just coincidental? I feel like using i in all the instances is wrong…

Explain it to me like I’m five, I don’t mind.

actual_insurance_costs = [1100.0, 2200.0, 3300.0, 4400.0, 5500.0, 6600.0, 7700.0]

#while loop to determine total insurance costs
i = 0
total_cost = 0
while i < len(actual_insurance_costs):
  total_cost += actual_insurance_costs[i]  
  i += 1
# print statement to print out final total cost - not part of project. I wanted to see the value
print("this is the total cost " + str(total_cost))

# original for loop
# total_cost = 0
# for cost in actual_insurance_costs:
#     total_cost += cost

acutal_insurance_costs is a list.

Python uses zero-based indexing i.e. the first element is at index 0, the second element is at index 1, and so on. The len function tells us the length i.e. how many elements are in the list.

actual_insurance_costs = [1100.0, 2200.0, 3300.0, 4400.0, 5500.0, 6600.0, 7700.0]

The length of this list is 7.

# First element is at index 0
actual_insurance_costs[0] ---> 1100.0
actual_insurance_costs[1] ---> 2200.0
...
actual_insurance_costs[5] ---> 6600.0
actual_insurance_costs[6] ---> 7700.0
# Since the length is 7, so the last element is at index 6
total_cost += actual_insurance_costs[i]
# can be thought of as: 
total_cost = total_cost + actual_insurance_costs[i]

i += 1
# is the same as
i = i + 1

In the while loop posted by you, i is initialized as 0 before entering the loop.

In each iteration of the loop, the element at the index i is added to the total_cost

# First iteration
total_cost = total_cost + actual_insurance_costs[0]
total_cost = 0 + 1100.0
# total_cost is now 1100.0

 # Second iteration
total_cost = total_cost + actual_insurance_costs[1]
total_cost = 1100.0 + 2200.0
# total_cost is now 3300.0

 # Third iteration
total_cost = total_cost + actual_insurance_costs[2]
total_cost = 3300.0 + 3300.0
# total_cost is now 6600.0
...

i += 1 is very important. If you forget to increment i inside the while loop, you will be stuck in an infinite loop. If you omit this statement, i will remain as 0, the condition i < len(actual_insurance_costs) will always be True and you will be stuck in an infinite loop.

1 Like