Check if object is int or float: isinstance()
The type of an object can be obtained with the built-in function type().
i = 100 f = 1.23 print(type(i)) print(type(f)) # <class 'int'> # <class 'float'>
The built-in function isinstance(object, type) can be used to determine whether an object is of a particular type.
Get / determine the type of an object in Python: type(), isinstance()
print(isinstance(i, int)) # True print(isinstance(i, float)) # False print(isinstance(f, int)) # False print(isinstance(f, float)) # True
In this case, since only the type is checked, it cannot be determined whether the value of float is an integer (the fractional part is 0).
f_i = 100.0 print(type(f_i)) # <class 'float'> print(isinstance(f_i, int)) # False print(isinstance(f_i, float)) # True source: check_int_float.py Check if float is integer: is_integer() float has is_integer() method that returns True if the value is an integer, and False otherwise. f = 1.23 print(f.is_integer()) # False f_i = 100.0 print(f_i.is_integer()) # True
For example, a function that returns True for an integer number (int or integer float) can be defined as follows. This function returns False for str.
def is_integer_num(n): if isinstance(n, int): return True if isinstance(n, float): return n.is_integer() return False print(is_integer_num(100)) # True print(is_integer_num(1.23)) # False print(is_integer_num(100.0)) # True print(is_integer_num('100')) # False
Credits: https://note.nkmk.me/en/python-check-int-float/
input()function always returns an object of typestr. You can convert it to other types yourself if you want to.cis alwaysstrc=float(input("Enter a number")so it always show float. Any solution?