Use isinstance.
>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True
So:
>>> if isinstance(x, int):
print('x is a int!')
x is a int!
In case of long integers, the above won't work. So you need to do:
>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False
Answer from user225312 on Stack OverflowUse isinstance.
>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True
So:
>>> if isinstance(x, int):
print('x is a int!')
x is a int!
In case of long integers, the above won't work. So you need to do:
>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False
I like @ninjagecko's answer the most.
This would also work:
for Python 2.x
isinstance(n, (int, long, float))
Python 3.x doesn't have long
isinstance(n, (int, float))
there is also type complex for complex numbers
Videos
while True:
while True:
print("Enter a number")
num1 = input("")
if (num1.isfloat()):
break
else:
continue
while True:
print("Enter a second number")
num2 = input("")
if (num2.isfloat()):
break
else:
continue
For context. I'm writing a super simple, two number calculator. And i wanted to write a section where it tests for a float. So when you type in a number, for number 1 (the variable is called num1), python is suppose to check if it is a float or not. And if it it, it will continue the script if it is. And ask for the number again if its not. However, I'm struggling to find the right syntax to check for a float. isdigit and numeric work, but for some reason isfloat() does not work for me. What am I typing wrong, I'm quite new to programming.