How can I tell if the variable is an integer in Python?
I know how to do this in PHP:
is_int($variable); // bool(true)
But how can I do it in Python?
Example:
numero = 1 #é numero
nao_eh_numero = 'texto' # não é número
How can I tell if the variable is an integer in Python?
I know how to do this in PHP:
is_int($variable); // bool(true)
But how can I do it in Python?
Example:
numero = 1 #é numero
nao_eh_numero = 'texto' # não é número
isinstance
Pass as the first parameter the variable you want to validate and the second parameter type.
Example:
isinstance(numero, int) # True
Note
If you want to validate if the variable is a number , using Python 2. You will need to change the second parameter to (int, long)
, in Python 3 this is not necessary because% / p>
isinstance(numero, (int, long))
long
type(numero) == int # True
The difference between the two is that type
also validates if the object is derived from the class (a child class). That is, it checks the entire inheritance structure of the object. isinstance
returns only the exact type.
Example to illustrate
class MinhaClasseInt(int):
pass
x = MinhaClasseInt(0)
type(x) == int # False
isinstance(x, int) # True
I would do it differently and more easily. Here's how:
numero = float(input('Digite um numero qualquer :'))
if(numero // 1 == numero):
print('\nNúmero inteiro !')
else:
print('\nNúmero Decimal !')
Notice that number 1 returns only the whole part; so if this division returns the number itself then it is an integer.
In fact this // does not even have to be done, just ask:
if int(numero) == numero:
But using both type
and isinstance
, if the contents of the variable are typed with a decimal point (12.0, for example), the variable will be float
and the expression result will be False
, even the number being integer.
I think this answer gets better:
if numero // 1 = numero: # se for True o número é inteiro
This works even if it is a variable type float
.