[Tutor] bug in exam score conversion program

W W srilyk at gmail.com
Sat Oct 4 13:28:59 CEST 2008

On Sat, Oct 4, 2008 at 5:11 AM, David <ldl08 at gmx.net> wrote:

> Hello!!


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

Wow! That's actually a really surprising way of solving this, and not
entirely bad. The easiest way of modifying this program is to do exactly
what you did with the "F"s, only with an "A".

I suspect most people would have created an if else chain:

if score >=  90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
    grade = "F"

print "Your grade is %s" % (grade, )

But in reality, there's nothing wrong with your method - as a matter of
fact, it's probably slightly more optimized (although we're talking in time
frames of < .00001 seconds) because rather than making comparisons it makes
one computation and then directly accesses the values stored in the tuple.

So, I'll compliment you for solving a problem in a way that I never would
have thought of, helping me to think outside the box! In addition a tuple is
an ideal variable here because it's constant - you cannot change the values
or size of a tuple, unlike a list or dictionary. Not that (at this point)
you're worried about malicious type users, but  it's always a good idea to
"fool proof" your code.

Well, I hope this helps both look at your problem a different way, as well
as solves your "bug" (in this case, a syntax error: the code behaves exactly
how it should, you just made an error in how you implemented your code.
Those will be your most common "bugs", from here until forever ;) )
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081004/c05dbe5a/attachment.htm>

More information about the Tutor mailing list