I'm having trouble understanding this
I tried:
if not None:
print('True')
Why does it print True?
Isn't the None
type supposed to be None
?
I'm having trouble understanding this
I tried:
if not None:
print('True')
Why does it print True?
Isn't the None
type supposed to be None
?
All Python objects have a truth value, see Truth Value Testing. That includes None
, which is considered to be false in a boolean context.
In addition, the not
operator must always produce a boolean result, either True
or False
. If not None
produced False
instead, that'd be surprising when bool(None)
produces False
already.
The None
value is a sentinel object, a signal value. You still need to be able to test for that object, and it is very helpful that it has a boolean value. Take for example:
if function_that_returns_value_or_None():
If None
didn't have a boolean value, that test would break.
4.1. Truth Value Testing
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
None
False
zero of any numeric type, for example, 0, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a bool() or len() method, when that method returns the integer zero or bool value False.
In Python None
is a singleton. It is called the null
in other languages.
In your if not None:
, the compiler assumes that not None means non empty, or non-zero and we know an if statement evaluates non-zero values as True
and executes them.
Function Examples:
1) if not None:
prints argument x in test()
def test(x):
if not None:
print(x)
>>> test(2)
2
2) if 1:
prints argument x in test()
def test(x):
if 1:
print(x)
>>> test(2)
2
3) if -1:
prints argument x in test()
def test(x):
if -1:
print(x)
>>> test(2)
2
4) if 0:
does not prints argument x in test()
def test(x):
if 0:
print(x)
>>> test(2)
5) if True:
prints argument x in test()
def test(x):
if True:
print(x)
>>> test(2)
2
Each value has a property known as "truthiness". The "truthiness" of None
is False
. This is so for several reasons, such as clean code when you consider a return value of None
to be failure or False
.
"Empty" objects like ''
, []
, 0
, or {}
all evaluate to false. Note that this doesn't include objects like 'None'
(the string) or '0'
.
So if not None
converts None
to False
.
"Truthiness" is also known as "booleaness", which is more formal in some contexts.
[Irony mode on]
If you are not happy printing True
you can make it print False
:
if not None:
print('False')
Now it prints False :)
EDIT: If you are worried about why it doesn't print None
instead of True
or False
(or Apples
) you can just make it print None
:
if not None:
print('None')