Python - How To Check if Input Is Integer in Python

ID : 85

viewed : 104

Tags : PythonPython StringPython Input

vote vote


In the world of programming, we work very frequently with the input of the user. Python has the input() function available, which allows the user to enter the desired input. Sometimes we may want the input of a specific type.

However, this function converts the user’s input to a string before compiling it with the program. Therefore, it is not simple to use the traditional methods to check for specific types with the user input, and we have to check whether the string contains numbers or not essentially.

In this tutorial, we will discuss how to check whether the input entered by the user is an integer type or not.

Use the int() Function to Check if the Input Is an Integer in Python

The int() function can convert a given string integer value to an integer type. It raises an error if the desired value is not an integer and cannot be converted. We can use this method to check if the user’s string is an integer or not, as shown below.

user_input = input("Enter the input ")  try:     int(user_input)     it_is = True except ValueError:     it_is = False  print(it_is) 


Enter the input 15 True 

Note the use of try...except block in this method. It is used very frequently when handling exceptions in Python.

Use the isnumeric() Method to Check if the Input Is an Integer or Not

The isnumeric() method of the string returns True if the string only contains numbers. However, it is worth noting that it fails with negative values. This is because it automatically returns False when it encounters the - sign in negative integers.

The following code shows how we can use this function to check if a string contains integers in Python.

user_input = input("Enter the input ")  print(user_input.isnumeric()) 


Enter the input 10 True 

We can also use the isdigit() function in place of isnumeric(); it also has the same limitations as this method.

Use the Regular Expressions to Check if the Input Is an Integer in Python

We can also use the regular expressions to create a pattern that returns True whenever it encounters integers in a string. We can also modify the pattern to make sure it works for negative values. For example,

import re  user_input = input("Enter the input ")  num_format = re.compile(r'^\-?[1-9][0-9]*$') it_is = re.match(num_format,user_input)  if it_is: print("True") else: print("False") 


Enter the input -15 True 

Below is the explanation of the regular expression pattern - ^\-?[1-9][0-9]*$.

  • ^ is the start of the string
  • \-? indicates that this number could be negative or positive.
  • [1-9] is the first digit of the number. It must be a number between 1 and 9, but not 0.
  • [0-9]* indicates the following digits. The number of digits could be any, including 0.
  • $ is the end of the string.

  • Related HOW TO?