0
user_input = int(input('Enter input: '))

if type(user_input) == "<class 'int'>":
    print('This is a integer.')

The code above outputs nothing to the console. I am just confused because it is very simple and looks like it should work.

I've tried removing the int() in the input line which output nothing, I understand this because user_input turns into a string but I do not understand why it outputs nothing when user_input is defined as an integer.

Calabran
  • 11
  • 2
  • 3
    use `isinstance(user_input,int)`. Don't confuse a type with a string representation. In this particular case the type check is pointless. If the line above doesn't throw an error then of course `user_input` is an int. A better way to do what you seem to want to do is to use a `try ... except` block around the line that tries to convert a string to an int. – John Coleman Dec 03 '22 at 14:31
  • Because no type can ever be equal to any string, for the same reason that no integer can ever be equal to any string. Types themselves have their own type. – Karl Knechtel Dec 03 '22 at 14:37
  • 1
    (Some people will suggest that relying on try-except is bad and you should use string methods like `isdigit`. Those people are wrong - those methods check character properties, not whether a string can be parsed as an int. You'll fail on inputs like `-3`, because `-` isn't a digit. Trying to get the check right manually is needlessly error-prone compared to just letting `int` handle it, and the situation gets even worse if you're trying to parse floats instead of ints.) – user2357112 Dec 03 '22 at 14:37

3 Answers3

0

Fix

That is because type(user_input) returns a type, not a string, don't confuse yourself with what you see printed and the real thing. When you print something you only see a representation of the thing. Only if it's a string you can copy and compare it directly

print(type(type(user_input)))  # <class 'type'>

So you well understand, this is how it would work using type

if str(type(user_input)) == "<class 'int'>":
    print('This is a integer.')

if type(user_input) == int:
    print('This is a integer.')

if type(user_input) is int:
    print('This is a integer.')

Improve

The prefered way should be

if isinstance(user_input, int):
    print('This is a integer.')
azro
  • 53,056
  • 7
  • 34
  • 70
0

Its because you're comparing it to the wrong thing. if you did "type(user_input) == int" your program should work as expected.

Fatima
  • 1
  • 1
0

You can use the isinstance method as mentioned above or just directly compare to the int like:

user_input = int(input('Enter input: '))

if type(user_input) is int:
   print('This is a integer.')
SQZ11
  • 1
  • 2