Check if value is string or number [duplicate]

-2

10) Make an algorithm that checks if a given value is a String.

valor = str(input("Informe um valor: "))

if(type(valor) == str):
    print("É uma String!")

In the IDLE or Python Console of PyCharm, if I type:

valor = "João"
type(valor)

it returns:

<class 'str'>

I researched Google and heard about a isinstance ()

11) Make an algorithm that checks if a given value is a decimal type.

valor = input("Informe um valor: ")

if(isinstance(valor, float)):
    print("É um decimal!")
else:
    print("Não é um decimal!")

The code above, from question 11, results in a wrong output, because if I type 3, or 3.2, in both it returns "Not a decimal!"

I would like to know the answers to these 2 questions .. (use Python 2.7 or Python 3.7, both are in Virtual Environments with Anaconda)

I was able to do 14 exercises of 18, but these 2 and more 2 that maybe I post later, I could not.

    
asked by anonymous 08.11.2018 / 16:36

3 answers

1
  

Considering only the decimal system (without taking into account hex, octal, etc.):

valor='1'
while valor!='0':
    valor = input('Digite o valor:')
    try:
        print(float(valor),' É um numero')
    except ValueError:
        print(valor, 'É uma string')

Note:
With a little effort you can refine more to distinguish float integers.

See working at repl.it

    
08.11.2018 / 17:21
1
  

The code above, from question 11, results in a wrong output, because if I type 3, or 3.2, in both it returns "Not a decimal!"

The code depicts what is happening - the return value of input in Python 3 is always a string.

To check if the string can be used as an integer or a decimal number, you have to write more code. For example, strings have method .isdigit() that returns True if all the characters in the string are digits - this allows you to check if the string contains an integer.

You can also use the .count method and check whether the ". (or "," as you prefer) within the string is 1. The most practical way to check if it is a valid float number however is to try to convert it to float, and catch a possible error with a try / except - if is not a valid float.

a = input("digite coisas:")
try:
   b = float(a)
except ValueError:
   eh_decimal = False
else:
   eh_decimal = True

...

You may have mistaken yourself for some example you have seen of Python 2, input tries to interpret what is typed as if it were a Python expression. Then numbers are returned directly from the input as "int" and "float" (and text will usually give an error). In Python 2, the correct thing was to use raw_input instead of the input.

    
08.11.2018 / 16:45
0

Try this out

valor = "Joao"
if type(valor) is str:
    print("é string")
    
08.11.2018 / 17:31