How Do You Check for a NaN in Python?
Introduced in Python 2.6, the math module provides a math.isnan() method that returns true if the argument is not a number as defined in the IEEE 754 standards.
Install Python 2.6 or later
Since math.isnan() was first introduced in Python 2.6, you will need this Python version or later.
Import the math module
Before you can use the isnan() method, you must import the math module if you have not already done so. The proper syntax is: import math
Pass the variable in question to the math.isnan() method
Suppose you have a floating point variable a which has the value NaN, which is a special value defined in the IEEE floating point standard. Consider the following example code: a=float(‘nan’) You can test whether a is NaN by passing it to the math.isnan() method as in the following example code: math.isnan(a) This behavior can easily be verified from an interactive Python prompt. Note that if the entire math module is imported as described above, the math.isnan() method must be invoked with the syntax above, as attempting to invoke isnan() alone will produce an error. This is because isnan() is not defined in the local namespace. This error can be avoided either by calling it as math.isnan() or by using alternative import syntax, such as the following: from math import isnan
Proceed according to the result of the math.isnan() method
Since math.isnan() returns a boolean value, it can be used in conjunction with flow control syntax such as if statements. Assuming the existence of a doSomething() function, a test might look like this: if math.isnan(a): doSomething()