The isnan() function is under the math library, so to use this function, we first have to import the isnan() function.
Python isnan
Python isnan() is a built-in math function that is used to check whether a given input is a valid number or not. The isnan() function is used to determine whether the given parameter is a valid number or not. If given number x as a parameter is a valid Python number (Positive or Negative), isnan() function returns False.
Syntax
math.isnan(x)
The math.isnan() function takes only one parameter x that is any valid data type in python.
Return Value
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
Programming Examples
See the following code.
# app.py # Importing math library import math # Checking working of isnan() # When the number is integer print(math.isnan(15)) # When the number is float print(math.isnan(14.55)) # When the number is negative print(math.isnan(-34)) # When the number is not finite print(math.isnan(float('nan')))
Output
False False False True
In this program, 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.
Let’s see another example.
# app.py import math # checking isnan() values print(math.isnan(math.pi)) print(math.isnan(math.e))
Output
python3 app.py False False
Conclusion
To check for NaN values in Python, then use the isnan() function provided by the math library.
That’s it.