Skip to content
Advertisement

adding an assertion error for non numerical values

I am trying to add an additional assertion for values that aren’t numbers but I dont know how to go about it. I did try adding a and type(score) == float but it didn’t work, I received a value error saying a string cannot be converted to float. I just want the program to return the assertionerror message in the code when the value entered is negative and non numerical.

try:
   score = float(input('Please enter your grade: n'))
   assert score >= 0 and score <= 100 and type(score) == float
except AssertionError:
   print("Error, values must be between 0 and 100")
else:
  if (score >= 0 and score < 70):
    print('Your grade is an F')
elif (score > 69 and score <= 79):
    print('Your grade is a C')
elif (score >= 80 and score <= 82):
    print('Your grade is a B-')
elif (score >= 83 and score <= 86):
    print('Your grade is a B')
elif (score >= 87 and score <= 89):
    print('Your grade is a B+')
elif (score >= 90 and score <= 92):
    print('Your grade is an A-')
elif (score > 92 and score <= 100):
    print('Your grade is an A')

Advertisement

Answer

It looks like your user input something other than a float at the input() line. If you want this to be more resistant to things like that, you can separate out ValueError in your try/except case. ValueError will be thrown when a non-float-able value is passed to the float() function. Something like

try:
   score = float(input('Please enter your grade: n'))
   assert score >= 0 and score <= 100 and type(score) == float
except AssertionError:
   print("Error, values must be between 0 and 100")
except ValueError:
   print("Error, you must give a number")
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement