Skip to content

Python check if variable is number

  • by

In Python, you can check if a variable is a number using various methods depending on the type of numbers you want to consider (integers, floats, complex numbers) and the version of Python you are using. Here are a few common methods:

1. Using the isinstance() function:

variable = 42  # Replace this with your variable

if isinstance(variable, (int, float, complex)):
    print("Variable is a number.")
else:
    print("Variable is not a number.")

2. Using type() function:

variable = 42  # Replace this with your variable

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

3. Using isnumeric() method (for strings):

variable = "42"  # Replace this with your variable

if variable.isnumeric():
    print("Variable is a number.")
else:
    print("Variable is not a number.")

Note: the isnumeric() method only works for strings containing positive integers. If you need to handle more complex numeric cases, it’s better to use the isinstance() or type() functions to check for numeric types.

Python checks if the variable is a number example

Python example that checks if a variable is a number:

def is_number(variable):
    if isinstance(variable, (int, float, complex)):
        return True
    return False

# Test cases
num1 = 42
num2 = 3.14
num3 = 2 + 3j
str1 = "hello"
str2 = "42"

print(is_number(num1))  # Output: True
print(is_number(num2))  # Output: True
print(is_number(num3))  # Output: True
print(is_number(str1))  # Output: False
print(is_number(str2))  # Output: False

Output:

Python check if variable is number

In this example, we define a function is_number() that takes a variable as input and checks if it is an instance of any of the numeric types (int, float, complex). The function returns True if the variable is a number and False otherwise.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *