How to check if a variable is number in Python

How to check if a variable is number in Python

Python is a dynamically typed language, meaning that variables can change types during execution. Checking types helps ensure that your code operates correctly with the expected data types and avoids unexpected behavior.

Numeric types in Python include:

  • Integer (int) represents whole numbers, positive or negative, without any decimal point.
  • Floating-point (float) represents real numbers with a decimal point.
  • Complex (complex) represents numbers with a real and imaginary part.
age = 30 # int
pi = 3.14159 # float
complex_number = 1 + 2j # complex
Enter fullscreen mode
Exit fullscreen mode

While Python doesn’t have a single general “number” type, these three built-in types cover a wide range of numerical representations you’ll need for most programming tasks.

Remember boolean values are a subset of integers in Python. The bool type is a subclass of the int type, so True and False have integer values of 1 and 0, respectively. This is why you can use boolean values in arithmetic operations and expressions as if they were numbers.

# Boolean values as integers
print(True == 1) # Output: True
print(False == 0) # Output: True

# Boolean values in arithmetic operations
print(True + True) # Output: 2
print(True * 10) # Output: 10
print(False - 5) # Output: -5
Enter fullscreen mode
Exit fullscreen mode

For everyday number handling, checking for complex numbers might be unnecessary. You need to check for common numeric types like integers and floats. If you want to exclude booleans, you would need to add an additional check.

Using isinstance() function

The isinstance() function checks if an object is an instance of a class or a subclass thereof. It is used when you want to check if an object is derived from a specific class, including its subclasses. For example, isinstance(True, int) will return True because bool is a subclass of int.

def is_number(x): return isinstance(x, (int, float, complex)) and not isinstance(x, bool) print(is_number(42)) # True
print(is_number(3.14)) # True
print(is_number(10 + 5j)) # True
print(is_number("hello")) # False
print(is_number(True)) # False
Enter fullscreen mode
Exit fullscreen mode

The numbers.Number abstract class is part of the numbers module. It doesn’t represent a specific type of number but rather serves as a superclass for all numbers, including integers, floats, complex numbers, and other subclasses that represent numbers.

By using isinstance(x, numbers.Number), you’re essentially asking, “Is x a number of any kind?” This is useful when you want to allow any kind of number.

import numbers def is_number(x): return isinstance(x, numbers.Number) and not isinstance(x, bool) print(is_number(42)) # True
print(is_number(3.14)) # True
print(is_number(10 + 5j)) # True
print(is_number("hello")) # False
print(is_number(True)) # False
Enter fullscreen mode
Exit fullscreen mode

Using type() function

The type() function in Python is a built-in function that returns the type of the object passed to it. For example, if you pass an integer to type(), it will return <class 'int'>. It is used when you want to know the exact type of an object, not considering inheritance.

def is_number(x): return type(x) in (int, float, complex) print(is_number(42)) # True
print(is_number(3.14)) # True
print(is_number(10 + 5j)) # True
print(is_number("hello")) # False
print(is_number(True)) # False
Enter fullscreen mode
Exit fullscreen mode

In practice, isinstance() is often preferred for type checking in Python because it supports subclassing and thus, is more versatile.

Using a try/except block

The try/except block catches the ValueError that would be raised if the conversion is not possible. The conversion to a complex number is considered sufficient for checking if a variable is a number in Python because the complex number type is the most general number type in Python.

def is_number(x): try: if isinstance(x, bool): return False complex(x) # Attempt to create a complex number
 return True except ValueError: return False print(is_number(42)) # True
print(is_number(3.14)) # True
print(is_number(10 + 5j)) # True
print(is_number("hello")) # False
print(is_number(True)) # False
Enter fullscreen mode
Exit fullscreen mode

Discover more from Coursity

Subscribe to get the latest posts to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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