1

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)

martineau
  • 119,623
  • 25
  • 170
  • 301
rage
  • 35
  • 6
  • "I have no idea why, but every number gets it to print 'NOT'" because input() function takes the input in form of a **string** – muyustan Jun 15 '20 at 22:00
  • Does this answer your question? [How do I check if a string is a number (float)?](https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float) – muyustan Jun 15 '20 at 22:01
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) - [`input`](https://docs.python.org/3/library/functions.html#input) returns a string – wwii Jun 15 '20 at 22:09

1 Answers1

2

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')
Red
  • 26,798
  • 7
  • 36
  • 58