Needing to check if a variable is a number in Python is a very common operation.
Thankfully, Python makes it easy for us to do this with very little effort.
In this post, we'll learn how to check if a variable is a number in Python.
The best way to check if a variable in Python is a number is by using the
type() function and passing the variable in as a parameter.
From there, we just need to compare the returned value to the
Here's an example of how we can check if a variable is a number:
money = 100 type(money) == int # True
Another way to do this is by using the
isinstance() function. This function takes in two parameters, the first being the variable to check and the second being the type to check against.
Let's pass in the variable
money and the type
int to the
isinstance() function and see if it returns
money = 100 isinstance(money, int) # True
As expected, it return
If you know that your number is a float, you can use the
type() function to check if it is a float by passing in the variable as a parameter and comparing it to the
price = 19.99 type(price) == float # True
Also, you can use the
isinstance() function to check if a variable is a float by passing in the variable and the
float type as parameters.
price = 19.99 isinstance(price, float) # True
In this post, we learned multiple ways you can check if a variable is a number, either an
int or a
float, in Python.
Hopefully, this post has been useful to you.
Leave us a message!