How to Check if a Variable is a Number in Python

Working on a data validation project for a U.S.-based retail analytics company, I had to ensure that every input value in a Python script was a valid number before performing calculations.

At first, it seemed like a simple task, just check if a variable is numeric. But as I dug deeper, I realized there are multiple ways to handle this depending on the data type, input source, and use case.

In this tutorial, I’ll show you how to check if a variable is a number in Python using several easy and practical methods. Each method has its own advantages, and by the end, you’ll know which one best fits your situation.

Method 1 – Use the isinstance() Function in Python

The easiest and most Pythonic way to check if a variable is a number is by using the built-in isinstance() function.

This function checks if an object is an instance of a specified class or a tuple of classes. For numbers, we usually check against int and float.

Here’s how I use it in my projects:

a = 42
b = 3.14
c = "Python"
d = True

# Check if each variable is a number
print(isinstance(a, (int, float)))  # True
print(isinstance(b, (int, float)))  # True
print(isinstance(c, (int, float)))  # False
print(isinstance(d, (int, float)))  # True (since bool is a subclass of int)

I executed the above example code and added the screenshot below.

python check if variable is number

In this example, the isinstance() function returns True for integers and floats. Interestingly, it also returns True for True and False because bool is a subclass of int in Python.

If you want to exclude boolean values, you can modify the check slightly.

def is_number(value):
    return isinstance(value, (int, float)) and not isinstance(value, bool)

print(is_number(True))    # False
print(is_number(10))      # True
print(is_number(3.5))     # True

This is my go-to approach when I’m working with numeric data in Python and want a clean, readable solution.

Method 2 – Use the type() Function in Python

Another easy way to check if a variable is a number is by using the type() function. Unlike isinstance(), type() checks for an exact match and doesn’t consider inheritance. This means it won’t treat bool as a number.

Here’s an example:

x = 25
y = 8.9
z = "25"
w = True

print(type(x) in [int, float])  # True
print(type(y) in [int, float])  # True
print(type(z) in [int, float])  # False
print(type(w) in [int, float])  # False

I executed the above example code and added the screenshot below.

python check if variable is a number

This method is ideal when you want strict type checking in Python. I often use type() when validating user inputs that must be strictly integers or floats, such as when processing numeric IDs or financial data.

Method 3 – Use try-except with Type Conversion

When working with user input or data imported from CSV files, values often come in as strings.

In such scenarios, one of the most reliable ways to check if a variable is a number is to try converting it to a float using a try-except block.

Here’s how I implement it:

def is_number(value):
    try:
        float(value)
        return True
    except ValueError:
        return False

# Test the function
print(is_number("123"))     # True
print(is_number("12.5"))    # True
print(is_number("Python"))  # False
print(is_number("NaN"))     # True
print(is_number(""))        # False

I executed the above example code and added the screenshot below.

check if variable is number python

This method is extremely useful when validating user input in Python applications.

It also works well for numeric strings like “123” or “12.5”, which can be converted to numbers. However, be cautious with special values like “NaN”, which technically count as numbers but may not behave as expected in calculations.

Method 4 – Use Regular Expressions (Regex) in Python

Sometimes, I need to validate numbers in string form before converting them. In such cases, regular expressions (regex) are a powerful tool.

Regex allows you to define a pattern that matches valid numeric formats, including integers, decimals, and negative numbers.

Here’s a simple implementation:

import re

def is_number_regex(value):
    pattern = r'^-?\d+(\.\d+)?$'
    return bool(re.match(pattern, str(value)))

# Test cases
print(is_number_regex("123"))    # True
print(is_number_regex("-45.67")) # True
print(is_number_regex("3.14.15"))# False
print(is_number_regex("Python")) # False

I executed the above example code and added the screenshot below.

check if variable is a number python

This method is great when you’re parsing text-based data, such as reading numeric values from log files or web forms.

I often use regex validation before converting strings to numbers, especially when working with APIs that return mixed data formats.

Method 5 – Use the numbers Module in Python

Python has a built-in module called numbers that provides abstract base classes for numeric types. You can use this module to check if a variable is a number (integer, float, or complex) in a more structured way.

Here’s how:

import numbers

def is_number(value):
    return isinstance(value, numbers.Number)

# Test cases
print(is_number(10))        # True
print(is_number(3.14))      # True
print(is_number(2 + 3j))    # True
print(is_number("Python"))  # False

This method is one of the most comprehensive ways to check for numeric types in Python. It even includes complex numbers, which can be useful in scientific computing or machine learning applications.

Method 6 – Check for Numeric Strings Using .isnumeric() and .isdigit()

Python strings have built-in methods like .isnumeric() and .isdigit() that can help identify if a string contains only digits.

However, these methods only work for positive integers and don’t handle decimals or negative signs.

Here’s an example:

num1 = "123"
num2 = "-45"
num3 = "3.14"
num4 = "Python"

print(num1.isdigit())   # True
print(num2.isdigit())   # False
print(num3.isdigit())   # False
print(num4.isdigit())   # False

These methods are limited but useful when you’re validating IDs, zip codes, or other strictly positive integer strings in Python.

Method 7 – Combine Multiple Checks for Robust Validation

In real-world Python projects, I often combine multiple methods to ensure robust validation. Here’s a function that uses both isinstance() and try-except for comprehensive checking:

def is_numeric(value):
    if isinstance(value, (int, float)) and not isinstance(value, bool):
        return True
    try:
        float(value)
        return True
    except (ValueError, TypeError):
        return False

# Test the function
print(is_numeric(100))       # True
print(is_numeric("45.6"))    # True
print(is_numeric("Python"))  # False
print(is_numeric(True))      # False
print(is_numeric(None))      # False

This approach is my favorite for production-grade Python scripts that deal with user-generated or external data sources.

So, these are some of the most effective ways to check if a variable is a number in Python. The isinstance() method is perfect for quick checks, try-except is best for user input validation, and the numbers module offers a professional, scalable approach.

Whenever I work on data-heavy Python projects, I rely on these methods to keep my code clean, error-free, and reliable.

You can also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.