Why am I getting a different value while running this for loop?

While doing Python Strings Medical Insurance project, in the extra exercise portion of it:

If I run the following code:

insurance_costs = [‘$7010.0’, ‘$4050.0’, ‘$12060.0’, ‘$7500.0’, ‘$3022.0’, ‘$4620.0’, ‘$16330.0’, ‘$2900.0’, ‘$19370.0’, ‘$7045.0’]

clean_digits_insurance =
total_insurance = 0.0
for i in insurance_costs:
clean_digits_insurance.append(float(i.strip(“$”)))
for n in clean_digits_insurance:
total_insurance += n

print(total_insurance)

#the total I received is 416567.0

However if I run it this way:

clean_digits_insurance =
total_insurance = 0.0
for i in insurance_costs:
clean_digits_insurance.append(float(i.strip(“$”)))
for n in clean_digits_insurance:
total_insurance += n

print(total_insurance)

#the total I received is 83907.0 (This being the correct amount)

I have completed the project, however I am still uncertain on why the amounts vary.

thanks for any help!

** I don’t know how to set it up here but in the first scenario the second for loop is a nested for loop

If the first case is a nested for loop, and the second case is just two for loops one after the other, then the reason that you’re getting a much higher value in the first case is that you increase total_insurance for every value in insurance_costs. For example:

insurance_costs = ['$17', '$18']

clean_digits_insurance = []
total_insurance = 0.0
for i in insurance_costs:
  clean_digits_insurance.append(float(i.strip(“$”)))
  for n in clean_digits_insurance:
    total_insurance += n
    #for the first iteration, tota_insurance is 17, as you'd expect
    #However, for the second iteration (as there are two values in the insurance_costs array
    #you increment totql_insurance by 18+17, which means it's actually 52
    #rather than 35

In the second instance; however, as the loops are not nested, you build the clean_digits_insurance array first, and then loop through it, meaning you don’t recount each value for every item in insurance_costs.

I hope that helps!

3 Likes

Thank you very much for your response! it makes perfect sense. I appreciate you taking your time to provide me with an answer to my question!

1 Like