How to make a loop that compares string with a float in python?

6

I'm assigning the 1.5 value to the h variable, but it does not accept values of type float and does not end the code.

h = (input("Informe sua altura: ")) # aqui ele recebe um elemento qualquer

while h != float:  # aqui faz a comparação(se fosse float deveria proceder)
    h = (input("Informe sua altura: "))  

    if h == float:
        print(h)
    
asked by Adriano Souza 13.07.2016 в 15:25
source

2 answers

5

Simple attempt to transform into float (with this you can know if the string typed has the same format as a float):

h = input("Informe sua altura: ")
try:
    float(h)
    print('É float, altura: ' ,h)
except ValueError as err:
    print('Não é float')

Repetition of input , no function:

while True:
    h = input("Informe sua altura: ")
    try:
        float(h)
        break
    except ValueError as err:
        print('formato errado')
print('altura:', h)

Repetition of input , with recursive function:

def return_float():
    h = input("Informe sua altura: ")
    try: 
        return float(h)
    except ValueError as err:
        print('Formato errado, por favor tente outravez')
    return return_float()
print('a sua altura é', return_float())

At last to follow your logic and for what you asked me in the comment, "... I can not use neither try nor except ...", you can do this:

while True:
    h = input("Informe sua altura: ")
    if h.replace('.', '', 1).isdigit():
        break
    print('formato errado')
print('altura:', float(h))
    
answered by 13.07.2016 в 15:32
3

Explicit casting is missing for float :

h = float(input("Informe sua altura: "))

See more here .

    
answered by 13.07.2016 в 15:33