[Tutor] bug in exam score conversion program
Alan Gauld
alan.gauld at btinternet.com
Sat Oct 4 15:45:46 CEST 2008
"David" <ldl08 at gmx.net> wrote
> I am quite happy with my code, but there is a bug: if the score is
> 100, then the program calculates 100/10 = 10. However, the tuple
> runs to 9, leaving me with an error message: IndexError: tuple index
> out of range
>
> I can't figure out how to solve that problem...
> I also suspect that my code clearly exposes me as a beginner :-)
> What would be the pythonic way of solving that exercise?
>
> # exam score to grade conversion
> # Zelle, ch. 4, exercise 7
> x = ("F", "F", "F", "F", "F", "E", "D", "C", "B", "A")
> score = raw_input("What's your exam score (0-100)? ")
> grade = x[int(score)/10]
> print "Your grade is:", grade
It's not too bad but I would probably use a dictionary rather
than the list - which avoids the index problem - and I'd do
the int conversion with raw_input::
Grades = {0:'F', 1:'F',2:'F',....8:'B', 9:'A',10:'A'}
score = int(raw_input("What's your exam score (0-100)? "))
print "Your grade is:", Grades[score/10]
HTH,
Alan G
More information about the Tutor
mailing list