How to check if a variable is number in Python | Python

 def is_number(x):
    return type(x) in (int, float, complex)

print(is_number(42))        # True
print(is_number(3.14))      # True
print(is_number(10 + 5j))   # True
print(is_number("hello"))   # False
print(is_number(True))      # False 

AI Explanation

This code defines a function named `is_number(x)` that takes a single argument `x` and returns True if the type of `x` is either `int`, `float`, or `complex`. Otherwise, it returns False. The function checks whether the type of the input `x` is one of `int`, `float`, or `complex` using the `type()` function. It then checks if the result is in the tuple `(int, float, complex)`. The function is then called with different types of inputs to demonstrate the behavior: - `is_number(42)` returns True because the input is an integer. - `is_number(3.14)` returns True because the input is a floating-point number. - `is_number(10 + 5j)` returns True because the input is a complex number. - `is_number("hello")` returns False because the input is a string, which is not one of the specified types. - `is_number(True)` returns False because the input is a boolean value, which is not one of the specified types.