0

I wanted to validate the data type as int or float in this simple code, I've gone wrong somewhere and the error message "Enter an integer!" shows up no matter what. I have already tried putting a == instead of != and putting all other statements after the if, but the problem persists.

def menuLoop():

    marks = input("Please Enter the Obtained Marks: ")
    if type(marks) != int or float:
        print("Enter an integer!")
        menuLoop()

    else:
        if int(marks) >= 75:
            print("A")
            menuLoop()
        elif marks >= 60:
            print("B")
            menuLoop()
        elif marks >= 35:
            print("C")
            menuLoop()
        elif marks < 35:
            print("D")
            menuLoop()



menuLoop()
  • Also, note that the function recursively calling itself until it gets a valid answer can lead to all sorts of problems. Use a loop instead. – Thierry Lathuille Feb 03 '19 at 12:27
  • You could have simply figured out what the problem is by using python interpreter, just execute `type(mark)`. And you would be able to find out what was the problem. Try some debugging first before posting question here. – letsintegreat Feb 03 '19 at 12:35

2 Answers2

0

In Python, the problem is that the input(), by default, is neither int nor float, that is a string.

If you want to check if the input is in the form of int, you can do that like this:

try:
    # mark is going to convert in int, if it can.
    # otherwise, it will throw a ValueError
    mark = int(mark)
except ValueError:
    # Handle the exception
    print 'Please enter an integer'
    menuLoop()

The function int() raises a ValueError, if the given parameter is not convertible in int. So, after catching that ValueError, we can show a message that to enter an integer value, like I've shown above.

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
0

This is a little tricky, but it will fix the logic, change your condition to:

if not marks.replace('.','',1).isdigit():
    print("Enter an integer!")
    menuLoop()

It will go inside the if if user inputs int or float.

.replace('.','',1) will replace only one . then check that all of the other characters are number or not.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59