How to check if a variable is a number in pyhon

Published on Aug. 22, 2023, 12:16 p.m.

To check if a variable is a number in Python, you can use the isinstance() function and pass the variable and the numbers.Number class as arguments. For example:

import numbers
x = 10
if isinstance(x, numbers.Number):
    print("x is a number")
else:
    print("x is not a number")

This will output “x is a number” because x is an instance of the int class, which is a subclass of numbers.Number.

If you want to specifically check if a variable is an integer, you can use the isinstance() function with the int class instead. For example:

x = 10
if isinstance(x, int):
    print("x is an integer")
else:
    print("x is not an integer")

This will output “x is an integer” because x is an instance of the int class.

Note that using isinstance() is a flexible way to check if a variable is a number or of a specific numeric type in Python.

Tags:

related content