Why am I getting a "TypeError: 'NoneType' object is not subscriptable" when it is suppossed to be indexing a list?

Question:

I am creating a game in pygame where a player moves their rectangle around and tries to go get points. It has a feature where it tracks high scores. The thing is, I keep on getting a "TypeError: ‘NoneType’ object is not subscriptable" error when I don’t know why. I believe the error occurs when you try to index something that can’t be indexed, but the thing is, I am trying to index a list where this error occurs.

I am not sure how I am supposed to let the program know that the variable is a function.

The two functions that are used (the second one is where the error occurs):

def get_scores(file_name):
    ''' returns a list of scores from the given file.
        Format of file must be:
             player 1 score
             player 2 score
            etc.
    '''
    f = None
    try:
        f = open(file_name)
    except:
        print(file_name + " does not exist. Reading failed")
        return
    scores = []
    # for loops automatically process file information line by line
    for line in f:
        # locate the comma, split the data and return a list of 2 items (player, score)
        score = int(line)
        scores.append(score)
    f.close()
    if len(scores)==0:
        print("Warning: high scores file is empty")

    return scores     
def update_high_scores(new_score, scores): #with help from luke Cue, adapted
    ''' if the new score makes the top scores, edits the given players and scores list with the new data'''
    for val in range(4):
        if new_score>scores[val]: #error occurs here
            scores.insert(val, new_score)
            scores.pop(5)

Here is where it is called:

myfile = "./unit 1_2/code/high_scores.txt"
myfile = "high_scores.txt"
scores = get_scores(myfile)
update_high_scores(points, scores)
text2 = font.render('high scores '+ str(scores), True, 'white', 'black')

And the error message:

Traceback (most recent call last):
  File "g:My Drive11th GradeAP Computer Science Principlesunit1_2final125proj.py", line 341, in <module>
    update_high_scores(points, scores)
  File "g:My Drive11th GradeAP Computer Science Principlesunit1_2final125proj.py", line 185, in update_high_scores
    if new_score>scores[val]:
TypeError: 'NoneType' object is not subscriptable
Asked By: amahd

||

Answers:

This can only happen if your function returns None. That can happen if the file you try to load in get_scores does not exist. In this case you would see your error message file_name + " does not exist. Reading failed".

Answered By: Alex Bochkarev
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.