How do I differentiate an int and float value for my program

Asked

Viewed 82 times

-2

Guys...so new in Python and wanted a help, I am making a calculator and I used the function isdigit() to avoid the error of the person putting a non-numeric character, however it recognizes only whole numbers, wanted help to solve this (for the calculator calculating broken numbers ) and also wanted help//tip to shorten the code.

a = False
b = True
c = True
tipo = input("(-,+,*,/)\nqual função vc deseja fazer ? \n")

if tipo == "-" or tipo == "+" or tipo == "*" or tipo == "/":
    a = True
else:
    print("caracter invalido!")
    
if a == True:
    primeiro_numero = input("qual o primeiro numero da função ? \n")
    
    if not primeiro_numero.isdigit():
        print("Digite apenas numeros")
        b = False
   
    if b == True:
        
        segundo_numero = input("qual o segundo numero da função ? \n")
        if not segundo_numero.isdigit():
            print("Digite apenas numeros")
            c = False
            
        if c == True:
            
            if tipo == "+":
                final = int(primeiro_numero) + int(segundo_numero)

            elif tipo == "-":
                final = int(primeiro_numero) - int(segundo_numero)

            elif tipo == "/":
                final = int(primeiro_numero) / int(segundo_numero)

            elif tipo == "*":
                final = int(primeiro_numero) * int(segundo_numero)
    
            print("O resultado é ",final)

3 answers

3


The most elegant way to test yourself is by using builtin isinstance.

Her use is isinstance(VARIAVEL, CLASSE)

Update: I used the term classe to understand that it is not necessarily a type primary.

See the example below:

>>> def is_int(x):
...     return isinstance(x, int)
...
>>> def is_float(x):
...     return isinstance(x, float)
...
>>> is_int(1)
True
>>> is_float(1)
False
>>> is_int(1.0)
False
>>> is_float(1.0)
True
>>>

I hope it helps

2

You can use:

try:
    numeroInteiro = int(input("Insira um numero inteiro: "))
except ValueError:
    print("Você deve inserir um valor inteiro!")

If the user enters anything other than an integer, it will trigger the exception, and this chunk works with any function of type, str(), float() and etc..

And in regards to shortening the code, in the operation selection part you can store all operations in a list, and use the operators not in to know if the user has selected a valid option.

print("(-,+,*,/) qual função vc deseja fazer ? \n")
operadores = ['-', '+', '*', '/']

tipo = ''

while(tipo not in operadores):

    tipo = input("Selecione uma opção adequada! ")

1

To differentiate types of variables in Python, there is the function type() which receives a variable per parameter, and returns a metaclass for the type of data stored in it.

Example to check if a variable stores a FLOAT: print(type(var) is float)

Example to check if a variable stores an INT: print(type(var) is int)

You can run the script below by varying the value of var.

var = 1.2
varType = type(var);

if varType is float:
    print("float")
elif varType is int:
    print("int")

Learn more

Browser other questions tagged

You are not signed in. Login or sign up in order to post.