0

I was trying to make a simple Python program which gets a user input through the variable "user_input" and then it determines the variable type through the function "type()." Here is a sample of the code:

user_input = raw_input('Enter something: ')
if type(user_input) == 'int':
    print "integer"
elif type(user_input) == 'str':
    print "string"

So you see, the code prompts the user to type down something, and if what they type down is an integer, it will print "integer" and if the input is a string type, it will print "string". The code does execute without an error message, but when I type down either a string value or an integer, it prints nothing, no spaces, no messages, N-O-T-H-I-N-G. Here is an example:

>>>
Enter something: hello
>>>

So since it is not working, I have to ask, is it possible for Python to even compare variable types of a user input and then go through an if / else statement?

  • It prints nothing because both tests fail. The types are int and str, not 'int' and 'str'. Anyway it's not the way to go. – S. de Melo Nov 03 '16 at 15:39

1 Answers1

1

You have two issues.

Firstly, type returns actual types, not string descriptions of types.

Secondly, the type of the return value of raw_input is always a string.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895