-5

Why do I keep getting the message wrong when I run this code in the python console? For a I enter 5.

a = raw_input("type a number here: ")

if type(a) != int == False:

    print ("Input verified!")

elif type(a) != float == False:

    print ("Input verified!")

else:

    print ("Wrong!")
miradulo
  • 28,857
  • 6
  • 80
  • 93

1 Answers1

4

type(a) != int == False is a chained comparison, and evaluates as:

(type(a) != int) and (int == False)

int == False is always going to be false.

Don't use == False or == True in boolean tests; just test directly or use not. Also, use isinstance() to test for specific types:

if isinstance(a, int):
    # ...

However, raw_input() returns an object of type str, always. It won't produce an object of type int or float. You need to convert explicitly using float(), and then use exception handling to handle inputs that are not valid integer or floating point numbers:

try:
    result = float(a)
    print 'Input verified'
except ValueError:
    print 'Sorry, I need a number'

Also see Asking the user for input until they give a valid response

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343