# Check for NaN values in Python #### David Y.

I sometimes see the value NaN (Not a Number) when working with floats in Python. How can I check whether a given value is NaN?

## The Solution

The best way to do this is by using the `isnan()` function from Python’s built-in `math` library:

```.css-8wixsa{display:block;position:relative;color:inherit;-webkit-transition:box-shadow 0.3s;transition:box-shadow 0.3s;will-change:box-shadow;outline:0;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;z-index:1;}.css-8wixsa:hover,.css-8wixsa:focus{cursor:pointer;}.css-8wixsa:hover .e1c139bc2,.css-8wixsa:focus .e1c139bc2{fill:#e1567c;cursor:pointer;}import math

nan = float('nan')
zero = 0
one = 1

print(math.isnan(nan))  # will print True
print(math.isnan(zero))  # will print False
print(math.isnan(one))  # will print False
.css-svqddq{position:absolute;z-index:10;background-color:black;float:right;top:2px;-webkit-align-self:flex-end;-ms-flex-item-align:flex-end;align-self:flex-end;color:#ffffff;display:none;}Click to Copy.css-1w9ozmm{position:absolute;z-index:10;height:20px;width:20px;fill:white;-webkit-align-self:flex-end;-ms-flex-item-align:flex-end;align-self:flex-end;background-color:black;display:block;}```

Note that `isnan()` will throw a `TypeError` if given a non-numeric value. Thus, a more robust implementation might look like this:

```import math

def is_nan(value):
try:
return math.isnan(value)
except TypeError:
return False

nan = float('nan')
zero = 0
one = 1
hello = "Hello!"

print(is_nan(nan))  # will print True
print(is_nan(zero))  # will print False
print(is_nan(one))  # will print False
print(is_nan(hello))  # will print False
Click to Copy```