Built-in Functions to Check Conditions in Python

Python provides several built-in functions that can be used to check conditions, types, or attributes of objects. These functions help in validating data and controlling the flow of programs.

1. isinstance()

Example:

num = 10
        print(isinstance(num, int))  # Output: True
        
        text = "Hello"
        print(isinstance(text, str))  # Output: True
        

Output

True
True

2. issubclass()

Example:

class Animal:
            pass
        
        class Dog(Animal):
            pass
        
        print(issubclass(Dog, Animal))  # Output: True
        print(issubclass(Dog, object))   # Output: True
        

Output

True
True

3. hasattr()

Example:

class Car:
            def __init__(self):
                self.make = "Toyota"
        
        car = Car()
        print(hasattr(car, 'make'))  # Output: True
        print(hasattr(car, 'model'))  # Output: False
        

Output

True
False

4. callable()

Example:

def greet():
            return "Hello"
        
        print(callable(greet))  # Output: True
        print(callable(5))      # Output: False
        

Output

True
False

5. len()

Example:

my_list = [1, 2, 3, 4, 5]
        print(len(my_list))  # Output: 5
        
        my_string = "Hello"
        print(len(my_string))  # Output: 5
        

Output

5
5

Conclusion

These built-in functions are essential for performing checks and validations in Python. They help ensure that the data types and structures used in the code behave as expected, promoting robustness and reliability in programming.