import math
numbers = [float('nan'), 1.0, -3.5, float('inf')]
for num in numbers:
print(math.isnan(num))
Output
True
False
False
False
Practical Differences:
NaN: Not a real number; cannot be used in calculations (results in NaN propagation).
inf and -inf: Valid but represent extreme values; still participate in arithmetic (e.g., inf + 1 = inf).
import math
numbers = [float('nan'), float('inf'), -float('inf'), 3.5]
for num in numbers:
if math.isnan(num):
print(f"{num} is NaN")
elif math.isinf(num):
print(f"{num} is Infinity")
else:
print(f"{num} is a valid number")
Use Case: Handling User Input: In data processing, isnan() can be used to detect invalid numbers from user inputs or sensor readings, preventing crashes.