lilboomer
lilboomer

Reputation: 11

Python - How to store a certain number of values

I have a program, which is a quiz and it stores scores depending on their class, the program also asks the teacher on which class they want to view, and in which way they can view the results, e.g. alphabetical, ascending order and the average of the class. I want the program to only store the person's last 3 scores.I have no clue on how to do this. Any help would be appreciated.

My code in writing the scores into the txt files looks like this:

count = str(count)

if classno == 1:
    abc = open("class1.txt" , "a" ,)
    abc.write(name)
    abc.write(",")
    abc.write(count)
    abc.write("\n")
    abc.close()

With count being the score they got, and there name, being there name.

My data in the text file looks like:

Test,10
Test,8
Test,2
Test,4
Geoff,2
Geoff,8
Geoff,4
Geoff,10
#etc.

I want it so it will overwrite there oldest score with there latest score, so it will only store 3 of there scores.

Upvotes: 0

Views: 492

Answers (4)

JamoBox
JamoBox

Reputation: 766

Have a function that will handle your last three scores:

scores = [10, 24, 37]
def update_score(score):
    if len(scores) < 3:
        scores.append(score)
    else:
        newscore = scores[1,2]
        newscore.append(score)
        scores = newscore

There's almost definitely a smarter way of doing this but it's late, I'm tired and writing this from my phone (no python interpreter at hand to test stuff), but you get the general idea.

Upvotes: 0

Zizouz212
Zizouz212

Reputation: 4998

I would use a dictionary object, like this: this_classes_scores = {}. This would allow you to store things like who got which score. However, if you don't need those specifics, a list would be fine (you can then look at Finn's answer).

class_a = {
    "bob": 75
    "joe": 85
    "dan": 99
    "mike": 1
    }

You can then access the information through indexing like print class_a['bob'] or you can iterate through them by calling the dictionary's method dict.itertools().

Upvotes: 0

michaelpri
michaelpri

Reputation: 3651

If you store the scores in a list, you can use indexing to get the last three scores

quiz_scores = [5,7,4,8,9,10]
if len(quiz_scores) < 3:
    store_scores(quiz_scores) #not a real function, just whatever you want to do with the scores
else:
    store_scores(quiz_scores[-3:]) 

Note: This will only work if you have the scores stored in order of time taken with the first score being the score the first time the quiz was taken and the last score being the score the last time the quiz was taken

Upvotes: 1

Finn
Finn

Reputation: 2089

You can use a List like

scores = [1, 2, 3]

scores.insert(0,'new')
scores.pop()
# scores is now ['new', 1, 2]

Upvotes: 1

Related Questions