Python isnan() method is a library method of math module, it is used to check whether a given number is “NaN” (Not a Number) or not, it accepts a number and returns True if given number is “NaN”, else it returns False.
math.isnan(x)
x
– a number that has to be checked whether it is “NaN” or not.The isnan() function returns two types of value:
True
: If the given parameter is not a number
False
: If the given parameter is a number
# python code to demonstrate example of
# math.isnan() method
# importing math module
import math
# math.isnan() method test on finite value
print(math.isnan(10))
print(math.isnan(0))
print(math.isnan(10.23))
print(math.isnan(0.0))
# math.isnan() method test on infinite and NaN value
print(math.isnan(float('inf')))
print(math.isnan(float('-inf')))
print(math.isnan(float('nan')))
Output
False
False
False
False
False
True
In the example above , we have imported the math library, and then we have checked the output of the isnan() function using various input.
We have checked output for integer, float, and negative numbers, respectively; for all these cases, the output is False. Then we have checked output for nan, here the output is True because nan is not a number.
import math
# checking isnan() values
print(math.isnan(math.pi))
print(math.isnan(math.e))
Output
False
False
If you want to check for NaN values in Python, then use the Python isnan() function provided by the math library.
Thanks for reading !
#python #programming