Check the type of input

Asked

Viewed 356 times

0

Good people! I need to do an input check for a job and I’m not getting this right. This is what I got till agr:

def verificação1():
     while True:
        try:
            quantidade=int(input("Insira a quantidade: "))
            quantidade=str(quantidade)
            print("Insira um produto válido.")
            continue
        except:
            break

The purpose of this piece of code is to verify that the quantity is even an integer number and not a string or float for example. But when I run it doesn’t seem to work...

1 answer

0

Although I would put the statement of quantidade outside the try as a matter of context, what we want to try (try) is just to transfer the quantity to integer. You can do with recursiveness:

def verificação1():
    quantidade=input("Insira a quantidade: ")
    try: 
        return int(quantidade) 
    except ValueError:
        print("Insira um produto válido.")
        return verificação1()
print('A quantidade é {}'.format(verificação1()))

Or, doing with the cycle while as in your question:

def verificação1():
    while True:
        quantidade=input("Insira a quantidade: ")
        try:
            return int(quantidade)
        except Exception as err:
            print("Insira um produto válido.")
print('A quantidade é {}'.format(verificação1()))

In both examples to transform into str, can, out of function:

str(verificação1())

Although using some of these examples I find it unnecessary.

I’m not sure if it’s part of the question, but knowing doesn’t take up space. To know if a variable is of a specific type can:

hey = 'heya' # todos sabemos que é uma string
isinstance(hey, float) # False
isinstance(hey, str) # True

Browser other questions tagged

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