Table of Contents
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:
PYTHONmoney = 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.
PYTHONmoney = 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.
PYTHONprice = 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.
PYTHONprice = 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!
How to Install Node on Windows, macOS and Linux
Getting Started with Solid
Managing PHP Dependencies with Composer
Getting Started with Svelte
Create an RSS Reader in Node
Git Tutorial: Learn how to use Version Control
Best Visual Studio Code Extensions for 2022
Getting Started with Deno
How to deploy an Express app using Docker
How to deploy a Node app using Docker
Getting User Location using JavaScript's Geolocation API
Getting Started with Vuex: Managing State in Vue
