How to Check if variable in Python is a Number

Updated onbyAlan Morel
How to Check if variable in Python is a Number

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.

Checking if a variable is a number

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 int type.

Here's an example of how we can check if a variable is a number:

PYTHON
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 True or False.

PYTHON
money = 100 isinstance(money, int) # True

As expected, it return True.

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 float type.

PYTHON
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.

PYTHON
price = 19.99 isinstance(price, float) # True

Conclusion

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.

Happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.