Q:

# How do you check for a NaN in Python?

A:

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.

## Keep Learning

1. Install Python 2.6 or later

Since math.isnan() was first introduced in Python 2.6, you will need this Python version or later.

2. 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

3. 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

4. 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()

Sources:

## Related Questions

• A: Some options for learning the Python programming language include attending college classes, taking online courses or using online tutorials, or learning f... Full Answer >
Filed Under:
• A: The sqrt function in Python returns the square root of a given number. The syntax for the sqrt function is math.sqrt(x) where x equals any number greater t... Full Answer >
Filed Under:
• A: Python is an easy to use and relatively new programming language that you can use to do many things. For example, you could make a sentence all lowercase u... Full Answer >
Filed Under:
• A: User input in Python allows the program to gather information from a computer user. The program saves this input into a variable so that it can later be ma... Full Answer >
Filed Under:
PEOPLE SEARCH FOR