[Tutor] Python Programming for the Absolute Beginner - Chap 7 Q: 2

Alan Gauld alan.gauld at btinternet.com
Tue Aug 13 01:20:58 CEST 2013


On 12/08/13 01:52, Zack Hasanov wrote:

> I have the following code so far:
>
> def high_score():
>      high_scores = []
>
>      name = input("What is your name? ")
>      player_score = int(input("What is your score? "))
>      entry = (name, player_score)
>      high_scores.append(entry)
>      high_scores.sort(reverse=True)
>      high_scores = high_scores[:5]       # keep only top five

Note that you never read the stored values from your pickle file you 
just add a single value.

>
>      # dump scores
>      f = open("pickles1.dat", "wb")
>      pickle.dump(high_scores, f)
>      f.close()

This then dumps that single value to the file overwriting
anything that might have already been there.

>      f = open("pickles1.dat", "rb")
>      high_scores = pickle.load(f)
>      print(high_scores)

You then load the new value and print it.

> When I execute this program in the main() program I get only the
> existing single name, player_score list combination stored in the
> pickles1.dat file.

I have no idea how you call this. Presumably from within a loop?
But because you never read in the stored values before writing the new 
you only ever get the last value stored.

You need to insert code like your last block above at the top of the 
function to pre-populate high_scores before adding the new entry.

Once you get that working we can look at tidying up some
of the unnecessary code that will be left over, but lets
get it working first!

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list