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

Find if a Python object is a float or integer

To verify that a Python object is a number of type integer or floating, proceed as following:

  • In your Python Integrated development environment define your variable.
  • Use the built-in type() Python function to find the variable type
  • Optionally, check the variable type with an if statement to drive your program logic
# Python3

# define your numeric variable
my_number = 5 

# check the object type
var_type = type(my_number) 

# apply logic based on your variable type
if (var_type in [float, int]):
    print (f"The Variable {my_number} is a number of type:{var_type}" )
else:
    print (f"The Variable {my_number} is not a number")

This code will return the following result:

The Variable 5 is a number

Check object is numeric or character using numbers module

An alternative method to verify whether an object type is numeric is using the numbers module.

# Python3

# import the numbers library
import numbers

# define a string variable
my_number = '5' 

# verify variable is a number and apply logic
if isinstance(my_number, numbers.Number):
    print (f"The Variable {my_number} is a number of type:{type(my_number).__name__}" )
else:
    print (f"The Variable {my_number} is not a number")

Due to the fact that purposely we defined our variable as a string, it’s clear that the code will return the following result:

The Variable 5 is not a number

Make sure to import the numbers module into your Python IDE – Jupyter, VSCode etc’ before using it in your script. Failing to do so will return a nameerror exception when running your code.