The program is not recognizing whole number as such

Asked

Viewed 123 times

1

a = int (input ("insira um número :"))

if a != int :  
    print ("isto não é um numero inteiro") 

else :
   print ("seu número foi :"+ str(a))

I’m trying to make a program where the user puts a value and the program says what was the value that he entered, but if I inserted a letter, from this error screen.

It turns out that when he inserts a number the program does not recognize as such.

  • pass the variable in type() to be able to condition with its type: type(var) != int

  • 1

    It makes no sense to test the function return type int() because that function ALWAYS returns an object of type int! What you want is to capture the exception that occurs when the function int() tries to convert an invalid text; see the answer below

1 answer

2


Python, its standard functions, detects impossible conversions through an exception mechanism, so you have to capture the exception to identify that there was error, thus:

try:
    a = int(input("insira um número: "))
    print ("seu número foi: " + str(a))
except ValueError:
    print ("isto não é um numero inteiro")

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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