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

In this Python tutorial, I will show you how to check if a variable is a number in Python. We will see different ways to check if the Python variable is a number with illustrative examples, and we will also see some uses why we need to check the Python variable is a number.

In Python, a variable is a location in memory used to store some data (value). They are given unique names to differentiate between different memory locations. They can store different types of data types in Python.

Python’s three built-in Numeric data types are Integer, Float, and Complex numbers.

  • IntegersThe int class in Python represents this value. It contains positive or negative whole numbers (not fractions or decimals).
  • Float- The float class in Python represents this value. It contains positive or negative decimal numbers.
  • Complex number- A complex class represents a complex number. It is specified as (real part) + (imaginary part)j. For example, 5+8j.

How to Check if a Variable is a Number in Python [4 Methods]

There are four different ways to find out if Python variable is a Number:

  • Using isinstance() function
  • Using type() function
  • Using a try/except block
  • Using round() function

Let’s see them one by one with examples.

Method-1: Check if the Python variable is a number using the isinstance() function

The isinstance() function is a built-in Python function that checks if a variable is of a specific type. It takes two parameters: the variable and the data type, and it returns True if the variable is of the specified type, and False otherwise.

For example: Imagine we’re a data analyst working with the U.S. Census Bureau data. We might be dealing with a variety of data types in Python, including integers (like population counts) and strings (like state names).

population = 331449281  # U.S. estimated population in 2021
state = "California"

print(isinstance(population, int))
print(isinstance(state, int))

The output is:

True
False
Python check if value is number using isinstance function

Note: This approach only checks for one type at a time. If we want to check if a variable is either an integer or a floating-point number or a complex number, we can use a tuple with the isinstance() function.

For instance, we add one variable to the above example:

population = 331449281  # U.S. estimated population in 2021
state = "California"
unemployment_rate = 5.8  # U.S. estimated unemployment rate in 2021

print(isinstance(population, int))
print(isinstance(state, int))
print(isinstance(unemployment_rate, (int, float, complex)))

The output is:

True
False
True
python if variable is number using tuple of data types in isinstance function

This way we can use the isinstance() function to check if the variable is a number in Python.

Method 2: Check if the Python variable is a number using the type() function

The type() function in Python returns the type of the variable. This function can also be used to determine if a variable is a number.

For instance, Suppose we’re analyzing the average household size in the U.S., which can be a floating-point number in Python.

average_household_size = 2.53  # U.S. average household size in 2020

if type(average_household_size) in (int, float, complex):
    print("This is a number.")
else:
    print("This is not a number.")

The output is:

This is a number.
Python check variable is number using type function

This way we can use the type() function to check if the variable is a number in Python.

Method 3: Check if the variable is a number using the try/except block in Python

Another approach, especially useful when dealing with user input, is to use a try/except block in Python. This approach attempts to convert the Python variable to a numeric type, and if it fails (raising an exception), we know that the variable is not a number in Python.

For example, we’re developing an app in Python that asks the user to input the number of U.S. states they’ve visited using the input() function.

states_visited = input("Enter the number of states you've visited: ")

try:
    float(states_visited)  # Try to convert to a float
    print("This is a number.")
except ValueError:
    print("This is not a number.")

The Output is:

This is a number.
Python check if a variable is a number using try and except block

This way we can use try/except block in Python to check if a variable is a number.

Method-4: Check if the variable is a number using the round() function in Python

The round() function in Python is primarily used to round a number to a specified number of decimals, but it can also be used as a means to check if a variable is a number or not. This is similar to using the try/except block approach.

In Python, if we try to round a value that is not a number using the round() function, a TypeError will be raised. We can use this behavior in combination with a try/except block to test if a variable is a number.

For instance, Suppose we’ve two variables in Python one containing the name of the country and the other the number of states in that country. let’s check whether the data stored in Python is a number or not.

def is_number(variable):
    try:
        round(variable)
        return True
    except TypeError:
        return False

States = 50
Country = 'United states'


print(is_number(States))
print(is_number(Country))

The output is:

True
False
Python check if variable is number using round function

This way we can use the round() function with try /except block to check if the variable is a number in Python.

Conclusion

In this tutorial, we learned 4 different methods to check if a variable is a number in Python.

You may also like: