How to check if a variable is a number in Python
You can check if a variable is an integer using the type()
function, passing the variable as an argument, and then comparing the result to the int
class:
age = 1
type(age) == int #True
Or using isinstance()
, passing 2 arguments: the variable, and the int
class:
age = 1
isinstance(age, int) #True
You can check if the number is a floating point number by comparing it to float
instead of int
:
fraction = 0.1
type(fraction) == float #True
→ Get my Python Handbook
→ Get my Python Handbook
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025