-2

Here is the program:

score = raw_input("Enter your score between 0.0 and 1.0: ")
try:
    fscore = float(score)
except:
    print "Enter a numerical value for score."
    exit()
if fscore >= 0.0 and fscore <= 1.0:
    if fscore >= 0.9:
        print "A"
    elif fscore >= 0.8:
        print "B"
    elif fscore >= 0.7:
        print "C"
    elif fscore >= 0.6:
        print "D"
    elif score >= 0.5:
        print "E"
    elif score < 0.5:
        print "F"
else:
    print "Score is out of range."

This is a simple program to give grades to students based on their score. If you notice carefully, I have made a semantic error in the 4th elif statement. Instead of writing elif fscore >= 0.5, I have written elif score >= 0.5.

What's intriguing me is if I pass 0.4 in score, this program gives me output E. Shouldn't I receive an error? And even if I am not receiving an error, why E? Why not A or B or anything else?

1 Answers1

0

I believe this has something to do with the answer provided in this thread: Compare string to float in Python

Notice that you are actually comparing a string (the input of the user) to a float (the 0.5 set in your elif). Apparently it is a design bug.

Note: I did not know this up front either :)

Community
  • 1
  • 1
JustLudo
  • 1,690
  • 12
  • 29