0

I noticed something today while fiddling with my code:

print("lol") if None else print("Not lol") # Displays 'Not lol'
print("lol") if 0 else print("Not lol") # Displays 'Not lol'
print("lol") if float("nan") else print("Not lol") # Displays 'lol'

Unlike None and 0. Why is float("nan") not considered Falsy?

Cheers

Imad
  • 2,358
  • 5
  • 26
  • 55

2 Answers2

3

OP : Unlike None and 0. Why is float("nan") not considered Falsy?

Ans: Because that's what the language designers decided would be most useful.

print(bool(float('nan')))  # returns True

Hence:

print("lol") if float("nan") else print("Not lol")

OUTPUT:

lol
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • 1
    IMHO this does not answer the question. It just rephrases it into "Why language designers decided truthy NAN would be more useful than falsy NAN". What are reasons behind the decision? I believe this is what OP is actually interested in. – shitpoet Dec 07 '21 at 22:29
0

It's not falsy because it's a valid string argument for float. You can find more information in the documentation. https://docs.python.org/3/library/functions.html?highlight=float#float

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity.