Python: and/or operators strange behavior

Question:

I know that the AND operator has precedence over the OR operator. I also believe that like in C/CPP the associativity of these operators is from left to right (although it doesn’t seem to be crucial for my question).

I run the following code in Python 2.7.1:

Case 1:

I have three functions:

def f(): print 3; return True

def g(): print 4; return False

def h(): print 5; return False

When I run the following command

f() and g() or h()

I get

3
4
5
False

This is fine (what I expected).

Case 2:

If I change the functions to:

def f(): print 3

def g(): print 4

def h(): print 5

I get for the same command:

3
5

Case 3:

If I change the command to

 f() and (g() or h())

I get only:

 3

I know that in the last two examples, the functions do not actually return boolean value, but yet – I don’t understand this behavior. it seems inconsistent:

Do we refer the functions f(),h(),g() as True or as False or something alse (what?)?

Why in the second case, h() runs and not g()?

Why in the last case none of them (g and h) run?

Asked By: Gari BN

||

Answers:

In Python, a function that doesn’t explicitly return anything returns None. None is considered false in a boolean context.

In the second example, g doesn’t run because the and operator short-circuits. f‘s result was false, so g() doesn’t need to be evaluated, as its result won’t change the result of the whole and expression.

Similarly, in the third example, since f() was false, the right side of the and doesn’t need to be evaluated, so g and h don’t run.

Answered By: user2357112

Here, since the all the functions return None, When you say f() and g() or h(), the function g() is never evaluated. That is because, the first operand to and is False. But h() is evaluated because first operand to or is False.

Note: f() and g() or h() is same as (f() and g()) or h()

http://docs.python.org/2/reference/expressions.html#boolean-operations

Answered By: Buddhima Gamlath