0

As a user input on a Else,If, Elif statements, I only want to allow the user input to get a positive response from a number instead of letters or special characters. I have created a simple grading calculator. I am learning the basics and just playing around with different options.

So far I haven't tried anything

grade = input('what is your grade?')

if grade >= '90':
  print('A')
elif grade < '90' and grade > '79':
  print('B')
elif grade < '80' and grade > '69':
  print('C')
elif grade < '70' and grade > '59':
  print('D')
elif grade <'60':
  print('F')
else:
print('Please enter your grade')

I inserted a word instead of a number and the return is 'F'. I want the return to be "error" or any message I choose if a number is not inserted after the question.

khelwood
  • 55,782
  • 14
  • 81
  • 108
cchil32
  • 13
  • 1

1 Answers1

0

Use try and except. Complete code change is below.



check = True
grade = 0
while(check):
    grade = input('what is your grade?')
    try:
        if float(grade) >= 0:
            check = False
    except:
        print("Bad entry.")

if grade >= '90':
    print('A')
elif grade < '90' and grade > '79':
    print('B')
elif grade < '80' and grade > '69':
    print('C')
elif grade < '70' and grade > '59':
    print('D')
elif grade <'60':
    print('F')
else:
    print('Please enter your grade')
Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35