How can I tell if the variable is an integer in Python?

6

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
    
asked by anonymous 10.01.2017 / 19:13

4 answers

11

Valid for Python 2 and 3

Using 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))

Using 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
    
10.01.2017 / 19:18
0

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.

    
19.08.2017 / 18:56
0

In fact this // does not even have to be done, just ask:

if int(numero) == numero:
    
25.10.2017 / 04:18
-2

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 .

    
13.08.2017 / 16:17