Home > Enterprise >  how to check if a variable contains int data and not float
how to check if a variable contains int data and not float

Time:07-04

so I need a program that checks if a variable is integer and it's not float data.

I tried this:

var = 2.5
if var is int :
    print(var)
else :
    pass

but this didn't work. can you help me on this? thanks.

CodePudding user response:

you can use simply the isinstance check

if isinstance(tocheck,int):
    print("is an int!")
elif isinstance(tocheck,float):
    print("is a float")
else:
    print("is not int and is not float!")

you could also use the type function but it doesn't check for subclasses so it's not recommended but provide anyways:

if type(x)==int:
    print("x is int")
elif type(x)==float:
    print("x is float")
else:
    print("x is neither float or int")

here are some useful links

CodePudding user response:

Just use isinstance() function:

if isinstance(var, int):
    ...
else:
    ...

CodePudding user response:

you can use the type method

https://www.programiz.com/python-programming/methods/built-in/type

print(type(var))

or

var = 2.5
if type(var) is int :
    print(var)
else :
    pass

CodePudding user response:

you can user type() here.

for example :

var = 2.5 if var is int : print(var) else : pass

  • Related