This python code lets a user enter in a numeric grade from which a letter output is given, but it also tries to take into account string user-inputs, or numeric user-inputs that are outside the range of 0.0 to 1.0, by delivering an error message as an output.
score = input("Enter Score: ")
try:
sr = float(score)
sr <= 1.0
sr >= 0.0
except:
print("Number entered must be between 0.0 and 1.0")
quit()
if sr >=0.9:
print ("A")
elif sr >=0.8:
print ("B")
elif sr >=0.7:
print ("C")
elif sr >=0.6:
print ("D")
else:
print ("F")
The issue I have is that when the user input is 1.2, I expect to get the error output I specified, "Number entered must be between 0.0 and 1.0". But instead I get an output of "A".
I understand that instead of using a 'try except' structure, I could use if statements to get the desired error message, but I just want to understand why the try-except code doesn't work the way I want it to.
Thanks bunches :).
P.S. First time posting, so apologies if I'm messing up with regards to stack overflow question etiquette or what have you.
This is what you are expecting...
score = input("Enter Score: ")
try:
sr = float(score)
assert sr <= 1.0 #needs an assert keyword
assert sr >= 0.0 #needs an assert keyword
except:
print("Number entered must be between 0.0 and 1.0")
quit()
If you don't write assert the sr <= 1.0
, it simply tries to compute the value and discard it as you are not assigning it to anything.
Alternatively you can use an if statement and quit in the if the condition doesn't match like this.
score = input("Enter Score: ")
sr = float(score)
if sr > 1.0 or sr < 0.0:
print("Number entered must be between 0.0 and 1.0")
quit()