Chrome Extension

Check if given value is a number or integer in python

To validate if a given value is a number or not, you can use below code examples. we are doing that using exception handling, python string isdigit() method.
#By throwing error
def check_int(value):  
  try:
    value_int = int(value)
    return 'Value is integer'
  except ValueError:
    return 'Not an integer'

check_int_response = check_int('20')
print(check_int_response)

# using isdigit() method - only for string format and positive values
value = "20"
if value.isdigit():
  print("value is integer")
else:
  print("value is not integer")
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

In the above code snippet, we are checking whether a given value is an integer or not. We have created a function check_int() and passing the value that needs to be checked as a parameter for this method.

try:
  value = "hello"
  convert_int = int(value)
except ValueError:
  print('Value is not integer type')
Python exception handling can be used to check whether the given value is a number or not. First, convert the value to integer type using the int() method inside the try block. If the value is not an integer type it will throw an error and will go into except block of ValueError.
In the code snippet, we have an integer variable and we are converting it to int. It will throw the error as the value assigned to this variable is not integer type.
value = "10"
if (value.isdigit()):
    print("Value is integer")
# -> prints Value is integer

# More examples
print("hello".isdigit()) # -> False
print("20".isdigit()) # -> True
Only works with string format value. Python method isdigit() can be used to check whether the given string value is an integer or not.
print("10".isnumeric()) # -> True
print("devsheet".isnumeric()) # -> False

val = "30"
if (val.isnumeric()):
  print("Value is an ineger type")
Only works with string format values like isdigit() method. You can use isnumeric() method of python to check whether the given value is a number or not.
In the code snippet, we are passing values and using value.isnumeric() syntax to check the value is and integer type or not. It will return True if the value is integer and return False if value is not a number.
import re

value = "-60"
regex_num = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
is_num = re.match(regex_num,value)
if is_num:
  print("Provided string is a number")
else:
  print("Not a number")
Works with negative values also. In the code snippet, we have imported regex using import re syntax and matching the regex against our value. If the string value is a number, it will return true and if the provided value is not a number it will return false.
Was this helpful?
0 Comments
Join Devsheet Ask a Question