False or None vs. None or False
The expression x or y
evaluates to x
if x
is true, or y
if x
is false.
Note that "true" and "false" in the above sentence are talking about "truthiness", not the fixed values True
and False
. Something that is "true" makes an if
statement succeed; something that's "false" makes it fail. "false" values include False
, None
, 0
and []
(an empty list).
The or
operator returns the value of its first operand, if that value is true in the Pythonic boolean sense (aka its "truthiness"), otherwise it returns the value of its second operand, whatever it happens to be. See the subsection titled Boolean operations in the section on Expressions in the current online documentation.
In both your examples, the first operand is considered false, so the value of the second one becomes the result of evaluating the expression.
You must realize that None
, False
and True
are all singletons.
For example, if foo is not None
means that foo
has some value other than None
. This works the same as just having if foo
which is basically if foo == True
.
So, not None
and True
work the same way. Also, None
and False
work the same way.
>>> foo = not None>>> bool(foo)True>>> foo = 5 # Giving an arbitrary value here>>> bool(foo)True>>> foo = None>>> bool(foo)False>>> foo = 5 # Giving an arbitrary value here>>> bool(foo)True
The important thing to realize and to be aware of when coding is that when comparing two things, None
needs is
, but True
and False
need ==
. Avoid if foo == None
and do only if foo is None
and avoid if foo != None
and do only if foo is not None
. In the case of if foo is not None
, simply do if foo
. In the case of if foo is None
, simply do if not foo
.
Note: True
is basically 1
and False
is basically 0
. In the old days of Python, we had only 1
for a value of true and we had 0
for a value of false. It's more understandable and human-friendly to say True
instead of 1
and more understandable and human-friendly to say False
instead of 0
.