Python Loops: Medical Insurance Project Extra Task (Convert for loop to a while loop)

Hello guys, nice to meet you all.

Here I have a question about how to convert a for loop to a while loop in this exercise.

Here is the for loop:
for insurance_cost in actual_insurance_costs:
total_cost += insurance_cost

New to programming, please don’t mind if I’m asking stupid questions!

Cheers and happy coding :slight_smile: Have a nice holiday!

Hello @patricio42, welcome to the forums! In this case, you would need to create a counter hint, hint variable to iterate through the list. You’d then have to use this variable to get each item from the array, then finally do something to the variable to stop the loop being infinite. I hope this has given you some ideas!

1 Like

Hello, I am experiencing the same issue.
Could I please have a hint on how can I convert the for loop in a while loop?
Thanks :slight_smile:

Hello @css2559983105 , welcome to the forums! When you have a for loop, there is essentially a built-in counter (the i in for i in range(0, 5), for example). When you use a while loop, you need to create a counter. That should be enough to get you started, but if you need more help, just let us know!

1 Like

@css2559983105 Reviewing this module helped me with the same question!


I was stuck too but you can actually add in another variable after total_cost = 0
(for example i = 0) and have it be less than the length of the list actual_insurance_costs. You would want it to be less than the length because “i” will be the index and if the length = 7 then you cannot have an index of 7 or higher.
Next, instead of incrementing total_costs by the insurance_cost, you will increment it by the actual_insurance_costs at index i. So:
instead of total_cost += insurance_cost → write total_cost+= actual_insurance_costs[i]
now you are including i as well
then you want to increment i by 1 to avoid an infinite loop (i += 1)
you can continue the rest of the code as before

so in the end you’d have something like this:

total_cost = 0
i = 0
while i < len(actual_insurance_costs):
total_cost += actual_insurance_costs[i]
i += 1