Python check if input is integer or String with Examples

In this article, We will check input is an integer or string in python. And also how to take user input as an integer also. There are many ways to check whether an input is a number or string.

  • Taking input as a string and convert it into an integer. (mentioned in below image)
  • Using built-in function called isdigit().It will check, whether the input is numeric or not
python check if input is integer

User input using input() function in python

Python supports a built-in function called input(), it allows user input. It takes input as string

OUTPUT

As you can see the output is a string. The input function can only obtain a string of text from the user. But if you want integer value, first you have take input data as a string and then convert it to an integer. For example:-

OUTPUT

The above code works fine if the user enters an integer. But by mistake, if the user enters any letter or punctuation signs, it will show an exception that is:-

Conversion into an integer is failed which is a value error, which you can see in the above example.

So, to avoid this kind of exception, we have to use Try/except/else. Using Try/except/else we can avoid this kind exception.

OUTPUT


Python Program to check user input is an integer or string

Take input from the user and convert it into an integer because as we explain above that input() function stores the input in a string. So, we have to convert it first, then next we Try/except/else to filter the input if any exception arrives.

OUTPUT


Python Program to check user input is an integer or a string using isdigit()

Python comes with a built-in function isdigit() which helps to determine whether the user input is number or not.

OUTPUT

You check how to input string in java here

Categories python