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 Svelte
- Getting Started with Express
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor