Python isinstance: Checking Variable Types

What is the isinstance function?

The isinstance function checks if a variable is an instance of a specified type or class. It returns True if the variable matches the type and False otherwise.

Why Use the isinstance function?

isinstance is useful for ensuring data types, which is valuable in functions that require specific input types. It helps prevent errors by validating inputs before processing.

Syntax

isinstance(variable, type)

Example

def check_input(data):
    if isinstance(data, int):
        print(f"{data} is an integer.")
    elif isinstance(data, str):
        print(f"{data} is a string.")
    elif isinstance(data, float):
        print(f"{data} is a float.")
    else:
        print("Unknown type")

check_input(1500)    # Output: 1500 is an integer.
check_input("Juan")  # Output: Juan is a string.

Scroll to Top