Check if a number is int or float
Fast and furious check if x
is int
or float
using isinstance()
function in Python:
Double-check: Including all numerical types
Beyond integers and floating point numbers, Python processes other numerical types such as complex and fractional numbers.
Remember numbers.Integral
checks for both plain and long integers.
Here, numbers.Real
checks if a value is any real number – int or float.
Extra mile: Explore different approaches
Crafty modulo trick
You can play the spy who loved integers, revealing their disguises:
By applying modulo (remainder) operation, we find out if the number has left any fractional part.
The try-except
hero
In a world where every line of code is a battle, try-except
comes to the rescue:
Here, int casting attempts to convert the number. A ValueError is your friend revealing the sneakiest floats and the baddest non-integers in town.
Stepping into the shoes of a number
Imagine numbers like containers filled with exact or spill-over amounts of liquid:
In Python, type checks can help determine the nature of these containers:
Buckets are int
. Spillers are float
.
Customizing the check
A function can encapsulate this check, for a cleaner and more reusable code pattern, because every hero deserves a clean home:
Mind the version
Remember, Python 2.x and Python 3.x are like Coke Classic and Diet Coke to integers. Treat int
and long
differently in 2.x:
- Python 2.x:
isinstance(n, (int, long, float))
- Python 3.x:
isinstance(n, (int, float))
# Python’s answer to Diet Coke –int
andfloat
are everything you need!
Types shape the operation
Remember, knowing the type is not for bragging rights, but to influence the operation's outcome. It can affect rounding and precision. So, pay attention, or your math could spill over.
Was this article helpful?