1

I have written this very simple program in python:

a=input('Enter the grade:')

if int(a)<5:
    print('D')
elif 5<=int(a)<10:
    print('c')
elif 10<=int(a)<15:
    print('B')
elif 15<=int(a)<=20:
    print('A')
elif 20<int(a):
    print('You idiot !')

else :
    print('Write a  number idiot !')

And the program will work if the user write a number, but if they write a string the program will give this error:

Traceback (most recent call last):
  File "C:\Users\sony\Desktop\Grader.py", line 2, in <module>
    if int(a)<5:
ValueError: invalid literal for int() with base 10: 'h'

How can I change the program, so that the users can write anything they want!

Mykola
  • 3,343
  • 6
  • 23
  • 39
user82087
  • 21
  • 1
  • Can you please elaborate on what you are exactly trying to do? What are your inputs and expected outputs? – Rubal Nov 19 '15 at 19:32
  • By the way. Calling users idiots would be a reason for me to fire somebody. – michel.iamit Nov 19 '15 at 19:37
  • Well i'm not your employee ! and that is an exercise program for beginners like me which my friend decided to make it a little fun ! do you think , we would call users idiot in a real program (like a project which we later have to write at the end of the semester) ? – user82087 Nov 20 '15 at 11:02

3 Answers3

1

modify:

a=input('Enter the grade:')

to:

a = None
while not a:
    try:
        a = int(input('Enter the grade:'))
    except ValueError:
        print("please enter a valid integer!)
    else:
        break
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

You can ether check the type of the variable or do a try / except. (Last is the easiest way, and see sufficiënt here)

michel.iamit
  • 5,788
  • 9
  • 55
  • 74
0

You can use this function to check whether the input value is an integer or not:

In [1]: def is_int(value):
...:     try:
...:         int(value)
...:         return True
...:     except ValueError:
...:         return False
...:     

In [2]: is_int(6)
Out[2]: True

In [3]: is_int('something')
Out[3]: False

Hope this helps!