How am I doing?

Jason jason at jasonmhirst.co.uk
Mon Sep 19 19:44:31 EDT 2005


I've restructured my code with the assistance of George and Mike which 
is now as follows...

import random

class HiScores:
     def __init__(self,hiScores):
         self.hiScores=[(entry[:5],entry[5:]) for entry in hiScores]

     def showScores(self):
         for name,score in self.hiScores:
             print "%s - %s" % name,score

     def addScore(self,score,name):
         score.zfill(5)
         bisect.insort(self.hiScores,(score,name))
         if len(self.hiScores)==6:
             self.hiScores.pop()

     def lastScore(self):
         return self.hiScores[-1][0]

def main():
 
hiScores=[('10000','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('00000','Epsilon')] 

     a=HiScores(hiScores)
     print "Original Scores\n---------------"
     a.showScores()

     while 1:
         newScore=random.randint(0,10000)
         if newScore.zfill(5) > a.lastScore():
             print "Congratulations, you scored %d " % newScore
             name=raw_input("Please enter your name :")
             a.addScore(newScore,name)
             a.showScores()

if __name__=="__main__":
     main()


However doing like the above (which DOES make sense now) raises a few 
questions that I've been struggling to find answers for over several 
hours now.

1) The most important is that when run, the program crashes with

Traceback (most recent call last):
   File "D:\My Documents\Development\Python\highscore1.py", line 35, in 
-toplevel-
     main()
   File "D:\My Documents\Development\Python\highscore1.py", line 28, in main
     if newScore.zfill(5) > a.lastScore():
AttributeError: 'int' object has no attribute 'zfill'

I've read as many websites as I can about zfill and I can't see why on 
earth it's failing.

2) The output of the predefined hiscores is now...

10000 - Alpha ()
07500 - Beta ()
05000 - Gamma ()
02500 - Delta ()
00000 - Epsilon ()

Why are there the pairing parenthesis there?  George very kindly showed 
me another way which was to have...

def showScores(self):
           for entry in self.hiScores:
               print entry[0:5]," - ",entry[5:]

But using that method output the entire list in it's full format (sorry 
if that's not the correct terminology).  But give me a small plus mark 
for changing code and not simply copying George :)

3) The hardest thing to 'understand' is the line...
	self.hiScores=[(entry[:5],entry[5:]) for entry in hiScores]

I 'understand' what it's doing, but I don't quite comprehend what the :5 
and 5: do.  I know that the :5 is technically saying from the start to 
position 5, and likewise the 5: would say from position 5 onwards, but I 
just can't get my head around how this works.

TIA




More information about the Python-list mailing list