How to find out the type of a variable given by the user?

3

I would like to ask the user to type something and find out what type of what he wrote. So far I only know input() , but input() only returns String type. If I by int(input()) or float(input()) fall into the same problem:

I can not do:

n = input()  
if n == int:  
  print('Tente novamente')  

and neither:

n = int(input())  
if n == str:  
  print('Tente novamente') 

I have already specified the type of the variable. How do I make the program find the type for me to do the condition based on its type?

    
asked by anonymous 15.12.2017 / 03:08

5 answers

5

Even if he types 1 or 1.0 will string anyway, string can be numeric format normally, just because 1 is a number does not mean that his type will be int .

What you can do is to use two to detect which format the string resembles and then cast , for example:

import re

entrada = input()

if re.match('^\d+$', entrada):
    entrada = int(entrada)
elif re.match('^\d+\.\d+$', entrada):
    entrada = float(entrada)

print(type(entrada), entrada)

The regex ^\d+$ of the first if will search from the beginning to the end of the string if it is numeric, without a dot.

The% regex% of the first ^\d+\.\d+$ will search from beginning to end of the string starting with numeric format until it reaches a point, once it reaches the point it will look for the number after it, if% will enter the if

Do not recognize any it will print as if same

About Python 2.7

Just to note, in Python version 2.7 the match would evaluate the content on its own (as if it were rolling "eval" ), then a script like this would be done:

entrada = input()

print type(entrada), entrada
  • When the input was string would return: input()

  • When the input was 1 would return: <type 'int'> 1

  • When the input was 1.0 would return: <type 'float'> 1.0

Then the equivalent of Python 3 "1" / em> for Python 2 would actually be <type 'str'> "1"

    
15.12.2017 / 03:33
1

Another simple way is to use ast.literal_eval .

So you do not open security holes by using the eval function, nor do you need to predict all input formats with regular expressions.

import ast

while True:
    entrada = input('Entre com alguma coisa:')
    valor = ast.literal_eval(entrada)
    print(type(valor))

See working at Repl.it

The result would be something like:

>>> Entre com alguma coisa: 1
<class 'int'>
>>> Entre com alguma coisa: 3.14
<class 'float'>
>>> Entre com alguma coisa: 1,2,3
<class 'tuple'>
>>> Entre com alguma coisa: [1,2,3]
<class 'list'>
>>> Entre com alguma coisa: '1'
<class 'str'>
>>> Entre com alguma coisa: "1"
<class 'str'>
    
04.09.2018 / 18:13
0

The answer is in the question. There's nothing to do. You will always know the value type, no matter how it is obtained and will know the variable type at that time. In fact, languages like Python do not have variable types, just a tag saying what type it is representing at the moment.

If the code already knows what type it does not have to figure out something.

If you are using a function that receives a value that can be of several types, you can use the function type() to identify the type of that object.

    
15.12.2017 / 03:26
0

Colleague, using the eval () method it is possible to get and interpret the value of the data inserted in the variable. Example:

numero = input()

try:
    if type(eval(numero)) == type(1):
        print("tipo inteiro")
    elif type(eval(numero)) == type(1.0):
        print("tipo real")
    else:
        print('não é um tipo numérico, %s' % type(numero))
except NameError as n:
    print('não é um tipo numérico, %s' % type(numero))

Maybe this is simpler. Lazy way mode .

    
15.12.2017 / 03:57
0

use the isinstance () function. Ex, I want to check something that the user typed, if it is an integer to select any option, just:

valor = input("Digite um valor inteiro") // usuario digita "a"
print(isinstance(valor, int) // Saida = False

Of course, the value that the user types will always be string, but with this function the understanding for conversion or post-conversion is easier.

    
04.09.2018 / 16:41