Python : The second for loop is not running

Files are not lists. You can’t loop over them without rewinding the file object, as the file position doesn’t reset to the start when you finished reading.

You could add results_f.seek(0) between the loops:

for each_line in results_f:
    (name,score) = each_line.split()
    scores.append(float(score))

results_f.seek(0)

for line in results_f:                      
    (name,score) = line.split()
    surfers.append(name)

but you’d be much better off by not looping twice. You already have the name information in the first loop. Just loop once:

for each_line in results_f:
    (name,score) = each_line.split()
    scores.append(float(score))
    surfers.append(name)

Your code only sorts the scores list; the surfers list will not follow suit. If you need to sort names and scores together, put your names and scores together in a list; if you put the score first you don’t even need to tell sort anything special:

surfer_scores = []

for each_line in results_f:
    name, score = each_line.split()
    surfer_scores.append((float(score), name))

surfer_scores.sort(reverse=True)  
print("The high scores are : ")
for i, (score, name) in enumerate(surfer_scores[:3], 1):
    print("{} - {}: {}".format(i, name, score)

Leave a Comment