Data type conditions in python

Question:

How do i give a condition in which for example; if x is not an integer print(“type an integer”)this image should explain better

Asked By: ebere

||

Answers:

With your sample code, your best bet is to catch the ValueError and try again:

def get_int():
    try:
        return int(input('Type an integer:'))
    except ValueError:
        print("Not an int.  Try again.")
        return get_int()

The reason is because if the user enters a non-integer string, then the exception gets raised before you have a chance to check the type, so isinstance doesn’t really help you too much here.

Answered By: mgilson

One way would be casting the value to into and handle the exception:

try:
    parsed = int(user_input)
    print ("int")

except:
    print ("not int")
Answered By: Ishay Peled