My code as a for loop that don't work

Hi,

I am a newbie and I had an exercise to do, but as I am trying to make a for loop that supposed to check all data in a .csv with the same “entity” as the user inputed to finally make an average of all life expectancy with the same entity over the years, the count is always = 0. (It’s on the country based research option, and the not working for loop is line 65 to 76)

Help I tried everything with my current knowledge:


            total_expetancy = 0
            count = 0
            for line in f:
                clean_line = line.strip()
                parts = clean_line.split(',')

                entity = parts[0].lower()
                year = int(parts[2])
                life_expetancy = float(parts[3])


                if entity == user_country.lower():
                    total_expetancy += life_expetancy
                    count += 1

            calculate_averages()

(The rest of the code work it’s just for the context)

It is because you are consuming the f iterator twice. Or in Layman’s terms: when you open a file and use for ... in f then that loop goes through entire file and so when you start yet another loop on the same variable, then that loop has nothing to iterate (because it is at the end of a file).

You have 2 options:

  • open a file twice
  • “Be Kind To Rewind”: f.seek(0)
1 Like

Oh ok thank you! I didn’t know that! You saved me!

1 Like

Stand corrected.

This is already how open works, it doesn’t read the whole file into memory when you iterate over the handle. read_line_in_file is totally redundant.