a shot of dev knowledge

RELATED TAGS

# How to assign NaN to a variable in Python

NaN, standing for not a number, is a numeric data type used to represent any value that is undefined or unpresentable.

For example, 0/0 is undefined as a real number and is, therefore, represented by NaN. The square root of a negative number is an imaginary number that cannot be represented as a real number, so, it is represented by NaN.

NaN is also assigned to variables, in a computation, that do not have values and have yet to be computed. Note: NaN is not the same as infinity in Python

## Assigning a NaN

We can create a NaN value in python using float, as shown below:

Note: Note that the “NaN” passed to the float is not case sensitive. All of the 4 variables come out as nan.

n1 = float("nan")
n2 = float("Nan")
n3 = float("NaN")
n4 = float("NAN")
print n1, n2, n3, n4

Note: You can also use Python’s Decimal library instead of floats. For example, you can do Decimal(“Nan”) instead of float(“Nan”).

NaN is also part of the math module in Python 3.5 and onwards. This can used as shown below:

import math

n1 = math.nan
print(n1)
print(math.isnan(n1))

math.isnan is used to check whether a certain variable is NaN or not. We cannot use the regular comparison operator, ==, to check for NaN. NaN is not equal to anything (not even itself!).

RELATED TAGS

RELATED COURSES
View all Courses
Related Courses
RELATED COURSES
View all Courses
Keep Exploring

Learn in-demand tech skills in half the time 