Search code examples
pythonif-statementinputintisinstance

Problem with checking if input is integer (very beginner)


I'm just starting to learn Python (it's my first language). I'm trying to make a simple program that checks if the number the user inputs is an integer.

My code is:

number = input('Insert number: ')

if isinstance(number, int):
    print('INT')
else:
    print('NOT')

I have no idea why, but every number gets it to print 'NOT'. If I just make a statement 'number = 1' in the code, it prints 'INT', but if I input '1' in the console when the program asks for input, it prints 'NOT' no matter what. Why is that?

(I'm using Python 3.8 with PyCharm)


Solution

  • When you input something, the type is always a str. If you try:

    number = input('Insert number: ')
    
    if isinstance(number, str):
        print('INT')
    else:
        print('NOT')
    

    you will always get:

    INT
    

    If all you want is to detect whether the input is an integer, you can use str.isdigit():

    number = input('Insert number: ')
    
    if number.isdigit():
        print('INT')
    else:
        print('NOT')