search

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

To check if a variable is a number in Python, you can use the isinstance() function or the type() function along with numeric types such as int, float, complex, or their subclasses. Here's an example:

# Using isinstance()
x = 10
if isinstance(x, (int, float, complex)):
    print("x is a number")
else:
    print("x is not a number")

# Using type()
y = 15.5
if type(y) in (int, float, complex):
    print("y is a number")
else:
    print("y is not a number")

In the above example, the isinstance() function is used to check if the variable x is an instance of any of the numeric types (int, float, complex). If it is, it prints "x is a number"; otherwise, it prints "x is not a number".

Similarly, the type() function is used to check if the type of the variable y is one of the numeric types (int, float, complex). If it is, it prints "y is a number"; otherwise, it prints "y is not a number".

You can modify the numeric types as per your specific requirements. Note that the isinstance() function is more flexible when checking against multiple types, as it allows passing a tuple of types as the second argument.

Keep in mind that these checks consider subclasses of numeric types as numbers as well. If you want to restrict the check only to the exact numeric types and exclude subclasses, you can specify the exact types in the isinstance() or type() function call.

Related Questions You Might Be Interested