Checking whether a variable is an integer or not
In Python, you can check if a variable is an integer using the isinstance()
function. The isinstance()
function takes two arguments: the first is the variable you want to check, and the second is the type you want to check it against.
Here's an example of how you can use isinstance()
to check if a variable is an integer:
x = 5
if isinstance(x, int):
print("x is an integer")
else:
print("x is not an integer")
In this example, the variable x
is set to 5, which is an integer. When we call isinstance(x, int)
, the function will return True
, and the code inside the if
block will be executed.
You can also check if a variable is any kind of number by using isinstance(x, (int, float, complex))
and similarly check other data types.
Another way to check if a variable is integer is using type()
function
x = 5
if type(x) is int:
print("x is an integer")
else:
print("x is not an integer")
It will give the same result as above but, this method is not recommended as it might cause issues in some cases.
And Finally, Python offers math.isinteger()
function which only checks if a number is integer, unlike above two methods which also check for other numeric type as well. For example:
import math
x = 5.0
if math.isinteger(x):
print("x is an integer")
else:
print("x is not an integer")
It will return False as x is float not an integer.