views:

153

answers:

5
In [20]: print None or False
-------> print(None or False)
False

In [21]: print False or None
-------> print(False or None)
None

This behaviour confuses me. Could someone explain to me why is this happening like this? I expected them to both behave the same.

+11  A: 

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).

RichieHindle
LOL, creative application of the recently coined term [truthiness](http://en.wikipedia.org/wiki/Truthiness), but fairly appropriate here, its questionable origins notwithstanding.
martineau
@martineau: It's a much older term in this technical sense. Colbert stands a better chance of mainstreaming it than programmers, but he's not the only source.
Roger Pate
Yeah, apparently a *much* older term. On Wiktionary for Etymology they indicate "First attested in 1824". I've never seen in used the technical sense that @RichieHindle did -- although it makes perfect sense in this case.
martineau
A: 

From a boolean point of view they both behave the same, both return a value that evaluates to false.

or just "reuses" the values that it is given, returning the left one if that was true and the right one otherwise.

sth
A: 
Condition1 or Condition2

if Condition1 is False then evalute and return Condition2. None evalutes to False.

Andrey Gubarev
+2  A: 

The 'or' operator returns the value of its first operand, if that value is true in the Pythonic boolean sense, otherwise it returns the value of its second operand. See the section titled Boolean operations in the current online Python v2.7 documentation.

In both your examples, the first operand is considered false, so the value of the second one is the result of the expression.

martineau
+1  A: 

A closely related topic: Python's or and and short-circuit. In a logical or operation, if any argument is true, then the whole thing will be true and nothing else needs to be evaluated; Python promptly returns that "true" value. If it finishes and nothing was true, it returns the last argument it handled, which will be a "false" value.

and is the opposite, if it sees any false values, it will promptly exit with that "false" value, or if it gets through it all, returns the final "true" value.

>>> 1 or 2 # first value TRUE, second value doesn't matter
1
>>> 1 and 2 # first value TRUE, second value might matter
2
>>> 0 or 0.0 # first value FALSE, second value might matter
0.0
>>> 0 and 0.0 # first value FALSE, second value doesn't matter
0
Nick T