0

I have a list of highscores (saved in a text file as the score, space, name (no commas)). However, when I go to retrieve the data, it appears only the first line is read.

for line in previous_scores:
    data = line.split()
    current_data = data[0]
    if int(current_data) > highscore:
        highscore = current_data
        highscore_names = [data[1]]
    elif int(current_data) == highscore:
        highscore_names.append(data[1])

For example, with the data below:

2 James
3 Anna
5 Emily

It would return the highscore as James, with his score being 2.

If my code is wrong could you please tell me what is wrong, and if your really awesome fix it. I don't mind if there is a better way to do this.

Edit:
The file is opened with:

previous_scores = open("Scores.txt", "a+")

Edit 2:
I added some extra lines on the end, and updated the code for testing to the following:

for line in previous_scores:
data = line.split()
current_data = data[0]
print "1 " + data[0]
print "2 " + current_data
if int(current_data) > highscore:
    print "3 " + current_data
    highscore = current_data
    highscore_names = [data[1]]
elif int(current_data) == highscore:
    print "4 " + current_data
    highscore_names.append(data[1])
elif int(current_data) < highscore:
    print "5 " + current_data

The first score always returns 1, 2 and 3, and then all other scores return 1, 2 and 5.

1 Answers1

4
    if int(current_data) > highscore:
        highscore = current_data

Here you convert the current highscore to a number, but store it as an unconverted string. Next loop you are comparing the next highscore as a number to the previously saved string.

I don't know what comparing number > string does in Python, but it's legal syntax and returns False, so you never save a higher highscore after the very first one.

Edit: Now I know, and it's interesting but irrelevant for this answer. https://stackoverflow.com/a/3270689/478656 and https://stackoverflow.com/a/2384139/478656

Community
  • 1
  • 1
TessellatingHeckler
  • 24,312
  • 4
  • 40
  • 77