Manoj Goswami
Manoj Goswami

Reputation: 1

Why it's giving me True as output as "None" is not a boolean type... so why "not None = True"

I tried this code to see what happens , but i cant get the logic behind it , i was expecting an error ... just for curiosity

python2.7

x = not None
print x

Upvotes: 0

Views: 544

Answers (3)

Andrew Li
Andrew Li

Reputation: 57924

Because not is a boolean type operator (a logical NOT), it converts None into a boolean. None as a boolean is False. The opposite of False, or not None is True, thus printing True.

>>> print(bool(None))
False

>>> print(not bool(None))
True

Upvotes: 1

user6451264
user6451264

Reputation:

None evaluates to False. The opposite of False is True. Thus, the result of not None is True. The boolean type conversion happens automatically, similar to what happens in 3 + True, which gives 4.

Upvotes: 0

happydave
happydave

Reputation: 7187

When Python evaluates not, it tries to convert the value to a boolean. In this case, None is "falsy" (https://docs.python.org/2.4/lib/truth.html), so not None evaluates to True.

So, x = not None is equivalent to x = True - i.e. you're assigning the variable x to be True.

Upvotes: 4

Related Questions