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.
JavaScript
x
21
21
1
try:
2
score = float(input('Please enter your grade: n'))
3
assert score >= 0 and score <= 100 and type(score) == float
4
except AssertionError:
5
print("Error, values must be between 0 and 100")
6
else:
7
if (score >= 0 and score < 70):
8
print('Your grade is an F')
9
elif (score > 69 and score <= 79):
10
print('Your grade is a C')
11
elif (score >= 80 and score <= 82):
12
print('Your grade is a B-')
13
elif (score >= 83 and score <= 86):
14
print('Your grade is a B')
15
elif (score >= 87 and score <= 89):
16
print('Your grade is a B+')
17
elif (score >= 90 and score <= 92):
18
print('Your grade is an A-')
19
elif (score > 92 and score <= 100):
20
print('Your grade is an A')
21
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
JavaScript
1
8
1
try:
2
score = float(input('Please enter your grade: n'))
3
assert score >= 0 and score <= 100 and type(score) == float
4
except AssertionError:
5
print("Error, values must be between 0 and 100")
6
except ValueError:
7
print("Error, you must give a number")
8