#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")
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')
value = "10"
if (value.isdigit()):
print("Value is integer")
# -> prints Value is integer
# More examples
print("hello".isdigit()) # -> False
print("20".isdigit()) # -> True
print("10".isnumeric()) # -> True
print("devsheet".isnumeric()) # -> False
val = "30"
if (val.isnumeric()):
print("Value is an ineger type")
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")
value_1 = 10
value_2 = 20.0
value_3 = "20"
value_4 = "Devsheet"
result_1 = isinstance(value_1, int)
print(result_1)
# -> True
result_2 = isinstance(value_2, int)
print(result_2)
# -> False
result_3 = isinstance(value_3, int)
print(result_3)
# -> False
result_4 = isinstance(value_4, int)
print(result_4)
# -> False
result_1_float = isinstance(value_1, float)
print(result_1_float)
# -> False
result_2_float = isinstance(value_2, float)
print(result_2_float)
# -> True
0 Comments