How to identify decimal and integer in Python

0

Good morning / afternoon / evening, I come here with the question of how to identify decimal and integer in python. Because I enter numbers with the float in case the user enters the decimal number. Then I want it to show an integer number in case the user enters a whole number and shows a decimal number in case there is a decimal number. Thanks for the attention.

    
asked by michael sornoza 22.01.2018 в 17:25
source

3 answers

0

Python assigns the data type dynamically, if the user enters a python integer the rest of the program will treat it as a whole, just as if it is a float. Therefore, if we print the variable that stores the input, it will be displayed as such.

You can try the following program and see how it works:

#Pedir el dato
dato = input('Ingrese dato: ') #Intenta introducir primero un entero y luego un decimal

print(type(dato)) #Ver de que tipo de dato es la variable
print(dato)

What I will show you is that if I enter an integer as a decimal python it will take it as a string, then if you want to do some type of calculation with that variable you would have to cast it: print(int(dato)) or print(float(dato))

    
answered by 22.01.2018 / 18:06
source
1

Complementing the response of @ Reynald0, it is not enough to check if the entry has a point '.' . They would also be float numbers such as 1e100 , 1e-2 e inf .

My advice is to check conversions and errors in this way:

dato = input("Ingrese dato: ")

num = None
for conv in (int, float, complex):
    try:
        num = conv(dato)
        break
    except ValueError:
        pass

if num is None:
    print("Error de entrada")
else:
    print(f"dato={num} (tipo: {type(num).__name__})")
    
answered by 22.01.2018 в 21:18
0

This can be a way to "deduce" the type of data.

Remember that input receives str (String) , that is, pure text. It is up to you to convert that text into the type of data you want.

This code only checks if there is a "." (period) in said entered text:

dato = input('Ingrese dato: ')

if '.' in dato:
    print("Seguramente es decimal", dato)
    print(type(dato))
else:
    print("Seguramente es entero", dato)
    print(type(dato))

Exit for "5.2" (str)

Ingrese dato: 5.2
Seguramente es decimal 5.2
<class 'str'>

Exit for "3" (str)

    Ingrese dato: 3
Seguramente es entero 3
<class 'str'>

In the if-else you would have to convert the data type str to the respective data type.

    
answered by 22.01.2018 в 19:00