How to check if a variable is a number in Python
By Flavio Copes
Learn how to check if a variable is a number in Python using type() or isinstance() to compare it against the int class, or float for floating point numbers.
You can check if a variable is an integer using the type() function, passing the variable as an argument, and then comparing the result to the int class:
age = 1
type(age) == int #True
Or using isinstance(), passing 2 arguments: the variable, and the int class:
age = 1
isinstance(age, int) #True
You can check if the number is a floating point number by comparing it to float instead of int:
fraction = 0.1
type(fraction) == float #True
What’s the difference between type() and isinstance()?
type() tells you the exact class of a value. isinstance() also accepts subclasses.
For a plain integer they agree. They disagree when inheritance is involved, and Python has a famous case of that: bool is a subclass of int.
type(True) == int #False
isinstance(True, int) #True
So if a True or False can reach your check, isinstance() happily reports it as an integer. That’s a real pitfall: a function validating “give me a number of items” accepts True and treats it as 1.
The fix is to exclude booleans explicitly:
def is_count(value):
return isinstance(value, int) and not isinstance(value, bool)
is_count(3) #True
is_count(True) #False
Or use type(), which doesn’t follow inheritance.
How to check for any number, int or float
Often you don’t care which kind of number you have, you just want “a number”. isinstance() accepts a tuple of classes, and matches if the value is any of them:
price = 19.99
isinstance(price, (int, float)) #True
quantity = 3
isinstance(quantity, (int, float)) #True
This is the version I use most in practice.
Note that the two classes are separate: an integer is not a float, so isinstance(3, float) returns False. That’s exactly why the tuple check exists.
Strings are not numbers
A string containing digits is still a string:
age = '35'
isinstance(age, int) #False
This bites you with user input, because input() always returns a string. If you want the number, convert it first with int(age) or float(age), and be ready for a ValueError when the string isn’t a valid number:
try:
age = int(input('Your age: '))
except ValueError:
print('That is not a number')