Grammy
Grammy

Reputation: 9

counting using a while loop nesting a for loop

I'm trying to print a quick 'top 5 high scores' list, everything else in the program is fine but in the last section using while loop with a for loop inside it and incrementing count in the for loop, the count increments but the loop does not stop. I don't know why, can anyone explain it to me? or give me a fix please.

import csv

with open ('gradesfile.csv' , 'w', newline = '') as file: # creates csv
    writer = csv.writer(file) # creates a python object to work with
    writer.writerow (['Akki', 55])
    writer.writerow (['Edna', 78])
    writer.writerow (['Bob', 67])
    writer.writerow (['Eave', 22])
    writer.writerow (['Albert', 45])
    writer.writerow (['Enrique', 81])


yourname = input('enter your name:')
yourscore = 99


with open ('gradesfile.csv' , 'a', newline = '') as file: # add to csv file
    writer = csv.writer(file)
    writer.writerow ([yourname,yourscore])

# create the sort of this info and display to the user
# Create a list to catch the highscores
highscores =  []

with open ('gradesfile.csv','r') as hfile:
    for line in hfile:  # loop over every line
        line = line.strip('\n')
        sline = line.split(',')
        name  = sline [0]
        score = sline[1]
        highscores.append((score, name))
        
#print (highscores)

highscores.sort(reverse = True)
#print(highscores)
print ('\n')
print ('B.O.A.T LIST')

count= 0  # creates count
while count<5:  # conditional loop to stop at 5 prints
    for item in highscores:    #loops over the tuples in the highscores list
        count +=1  # increments the count
        print ('PLAYER NAME : ', item[0], 'SCORE : ', item [1]) 
        print (count)  # demonstrate count is incrementing
    

Upvotes: 0

Views: 79

Answers (2)

Protik Nag
Protik Nag

Reputation: 529

This is because once the for loop started, the variable count has no scope to check the condition you provided in the while loop. This can be a solution:

count= 0
for item in highscores:    #loops over the tuples in the highscores list
    count +=1  # increments the count
    print ('PLAYER NAME : ', item[0], 'SCORE : ', item [1]) 
    if(count == 5)
        break

Upvotes: 1

The dickmaster
The dickmaster

Reputation: 67

The for loop doesn't necessarily have to stop when count >= 5. It depends on how many items there are in highscores.

Upvotes: 0

Related Questions