Struggling with basics
Reinhold Birkenfeld
reinhold-birkenfeld-nospam at wolke7.net
Sun Sep 25 14:47:44 EDT 2005
Jason wrote:
> A week ago I posted a simple little hi-score routine that I was using to
> learn Python.
>
> I've only just managed to examine the code, and the responses that
> people gave, and I'm now seriously struggling to understand why things
> aren't working correctly.
>
> At present my code is as follows...
>
> import random
> import bisect
>
> class HiScores:
> def __init__(self,hiScores):
> self.hiScores=[entry for entry in hiScores]
>
> def showScores(self):
> for score,name in self.hiScores:
> score=str(score).zfill(5)
> 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=str(random.randint(0,10000))
> if newScore > a.lastScore():
> print "Congratulations, you scored %s " % newScore
> name=raw_input("Please enter your name :")
> a.addScore(newScore,name)
> a.showScores()
>
> if __name__=="__main__":
> main()
>
>
> My first problem (lack of understanding of course) is that if I run the
> above, I get an error saying:
>
> print "%s - %s" % name,score
> TypeError: not enough arguments for format string
>
> Now I understand what it's saying, but I don't understand why.
The '%' operator expects a tuple or a single value on its right. So you
have to set parentheses around "name, score".
That needs getting used to, but otherwise it can't be discerned from
print ("%s - %s" % name), (score).
> If I change the code to read:
>
> print "%s - %n" % name, score (thinking of course that ah-ha, score is
> numeric) then I get the same error.
For integers you can use %s or %i (or %d), see http://docs.python.org/lib/typesseq-strings.html.
> Apologies for going over old ground and if I'm not understanding, I'm
> getting there honest ;)
No problem. c.l.py is newbie-friendly.
Reinhold
More information about the Python-list
mailing list