Python math.isnan() with example
In this tutorial, let’s learn about Python math.isnan() function with example.
The math module of Python contains the definition for math.isnan () function.
This function returns boolean values that are either true or false.
It returns True if the parameter is not a number otherwise it returns false for a valid number which could be positive or negative.
We need to import the math module to implement the isnan() method.
To learn more about the usage of the import statements, look into the link provided below.
import()__ Method in Python
Python math.isnan() function with example
Let’s see the code to understand the functionality of the isnan() function.
import math print(math.isnan(45))
OUTPUT : False.
Here, we have provided the parameter as some number 45.
Math.isnan function checks that the provided parameter 45 is a number. Since the given parameter is a valid number. Therefore, it returns the output as False.
Let’s check for a positive outcome.
import math x=float('nan') print(math.isnan(x))
OUTPUT : True.
In the above code, we could see a positive result since we have passed the parameter which is not a number.
Here we have float() to convert the string to a float value which is stored in the variable x. It is then passed as a parameter to check if it is a number or not.
Let’s see a few more examples.
The math.isnan() method also checks for a finite or infinite value. To understand it look into the following code.
Tests for infinite value.
import math print(math.isnan(float('inf'))) print(math.isnan(float('-inf')))
OUTPUT : False False
Tests for finite value.
import math print(math.isnan(30)) print(math.isnan(30.67)) print(math.isnan(0))
OUTPUT : False False False
Also read:
Leave a Reply