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

Asked

Viewed 11,566 times

5

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

I can’t do:

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

and neither:

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

Because I have already specified the type of the variable. How do I make the program discover the type so that I perform the condition based on her type?

5 answers

7


Even if he type 1 or 1.0 will be string anyway, a string can be numerically formatted normally, just because 1 is a number doesn’t mean his type will be int.

What you can do is use two to detect which format the string resembles and then do the 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)

A regex ^\d+$ of the first if will search from start to end of string if it has number format, no point.

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

Should you not recognize any he will print as string even


About Python 2.7

Just for the record, in Python version 2.7 input() evaluated the content on its own (as if "val"), so if you did a script like this:

entrada = input()

print type(entrada), entrada
  • When the input was 1 would return: <type 'int'> 1

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

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

So the equivalent of input() of Python 3 to the Python 2 actually would be the raw_input()

1

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

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

Of course the value that the user type will always be string, but with this function it is easier to understand for conversion or posteior conversion.

  • 1

    But I think this was not the question. As I said, if the return will always be string, the condition isinstance(valor, int) at all times will be false, so it makes no sense to use it. And if you use the int to convert, will fall in Maniero’s answer: if the program knows the type, have no reason to check. Then his reply was very confused and I could not understand what he meant. By the way, comments inline in Python is used #, nay //.

  • All the user types is string, however, I can convert a string "1" to int, but I can’t convert an str "a" to int. Although everything is string, not everything can be converted, understand? It can for example try to convert the input and then check if the conversion occurred correctly and isinstance() is a great way to do this. Used with Try except then, it would solve the problem. But I just wanted to add something. Most have written several lines to do the same thing as the function. As for the comments I am aware, but wanted to represent the debug if you did not understand.

1

Another simple way is to use the ast.literal_eval.

Thus, you do not open security loopholes using the function eval, or 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 on 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'>

1

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

If the code already knows what the guy is, there’s no reason to find anything.

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

  • The question is assuming precisely that I do not know what the user will write. If he writes an int() number the program will perform a certain action, if he writes a str() phrase the program will perform another action... So how do I find out the type of what he inserted?

  • What you’re talking about doesn’t exist. If you want to check the content of the text, then the question is totally other than what you wrote, like it’s something known.

  • Got it, so I’ll rephrase the question.

  • Then you will invalidate the answers already posted.

  • No no, I’ll ask another question, but asking "How to check the content of the text: if it is int, float or str?" It would be like this?

  • Yes. But it seems you’ve already accepted an answer here. This will not be useful for other people looking to find the type of the variable as it is in the question and not the text pattern of the data, as it seems to be the one you want.

Show 1 more comment

1

Colleague, using the Eval() method it is possible to take 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 will be simpler. Lazy way mode.

  • 1

    It is giving error when I put a string(). This appears: File "<string>", line 1, in <module> Nameerror: name 'test' is not defined

  • 1

    believe it now works. You can test. With Eval, when we insert a string it recognizes only values defined in the code.

  • 1

    It worked, now I have to learn how to use it... Thank you

  • 3

    Why exactly do type(1) and type(1.0) if you know the guys will be int and float?

  • 1

    It would only be to compare string results, but you can replace it with int or float or any other type you want. it will compare.

Browser other questions tagged

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