How to Check if variable in Python is a Number
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!
- Getting Started with Solid
- Getting Started with Svelte
- Getting Started with Express
- Create an RSS Reader in Node
- How to deploy a .NET app using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Using Axios to Pull Data from a REST API