The canonical way to check for the type of an object in Python is to use the isinstance function. Isinstance checks if an object is an instance of a specified class or of a subclass thereof.
Here's an example:
def check_type(obj): if isinstance(obj, int): return "Integer" elif isinstance(obj, float): return "Float" elif isinstance(obj, str): return "String" else: return "Other" print(check_type(42)) # Output: Integer print(check_type(3.14)) # Output: Float print(check_type("hello")) # Output: String print(check_type([1, 2, 3])) # Output: Other
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.