I am learning python using a book, one of the excersises is ; Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the following table: Score Grade >= 0.9 A, >= 0.8 B, >= 0.7 C, >= 0.6 D, < 0.6 F
I came up with the following;
inp = input('enter score: ')
try:
float(inp >= 0.00) and float(inp <= 1.00)
if inp >= 0.90:
grade = 'A'
elif inp >= 0.80:
grade = 'B'
elif inp >= 0.70:
grade = 'C'
elif inp >= 0.60:
grade = 'D'
elif inp < 0.60:
grade = 'F'
print('Grade: ',grade)
except:
print('bad score')
any input I input, regardless if it meets the conditions I set for the input or not comes out to the error message, "bad grade" Im not sure what I did wrong here honestly. Any help would be appreciated a lot.
CodePudding user response:
The only code inside a try
should be the code that can potentially raise an exception you want to handle. You should never use a bare except
like this --always handle specific exceptions, or at the very least Exception
.
The only operation that can throw an exception here is attempting to convert the user input (which is a string) to a numeric type, which will throw a ValueError
. You can also raise a ValueError
if the value isn't between 0 and 1:
try:
score = float(input("enter score: "))
if not (0.0 <= score <= 1.0):
raise ValueError
except ValueError:
print("please enter a decimal value between 0.0 and 1.0")
# Now do letter grade logic
With this try/except block, you can go one step further and wrap it in a loop that will keep asking the user for input until they enter a valid input:
while True:
try:
score = float(input("enter score: "))
if not (0.0 <= score <= 1.0):
raise ValueError
break
except ValueError:
print("please enter a decimal value between 0.0 and 1.0")
CodePudding user response:
A simple fix on the first line will make it working: (this is to make minimum change to your original code)
(Otherwise you will hit TypeError: '>=' not supported between instances of 'str' and 'float' on the first line)
However, it's preferrable to handle the expected Exceptions - such as ValueError... etc. Another suggestion is that to use a dictionary (mapping) for your score to grade, if the ranking/grading is known ahead of time.
inp = float(input('enter score: '))
try:
if 0.0 <= inp <= 1.00:
if inp >= 0.90: grade = 'A'
elif inp >= 0.80: grade = 'B'
elif inp >= 0.70: grade = 'C'
elif inp >= 0.60: grade = 'D'
elif inp < 0.60: grade = 'F'
print('Grade: ',grade)
except:
print('bad score')