Question

consider this code:

>>> 0 and True
0
>>> 0 and False
0

Why do I get 0 when I run the above commands in Python?

Was it helpful?

Solution

When the first condition of an and evaluates to False (which 0 does in Python), the second argument is not evaluated at all, because the and will never become true. This is called short-circuiting. In that case, the result of the expression is the first operand, in your case 0.

OTHER TIPS

Because 0 is a false value (all numeric 0 values are, as well as empty containers, and None and False).

The and operator short-curcuits; if the left-hand expression evaluates to a false value, it is returned, otherwise the right-hand expression outcome is returned.

The or operator does the same, but for a true left-hand value; 1 or False returns 1.

From the Boolean operations documentation:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

You can make handy use of this:

foo = None
if something_or_other:
    foo = lambda arg: arg * 3

outcome = foo and foo('bar')
outcome = foo or expensive_call()

where foo is only called if it is actually defined and not still None; the expensive_call() is only invoked if foo is not yet bound to a true value.

You are ANDing with zero. You should get zero always.

this is because, logical operators are evaluated from left to right. So, for or if True find rest of the expression not evaluated:

>>> True or "one"
True
>>> False or "one"
'one'

Similarly for and, if False found rest of the expression ignored:

>>> True and "one"
'one'
>>> False and "one"
False

In compiler design, this concept is called short-circuiting and this is same design for most of compilers.

most of programming languages have this feature, it's fast branch detection, in your case and if first condition is false, evaluation is fail and second (other) condition never check
in other case or if first condition return true second (other) condition never check and result will be true
it's really cool feature look this sample for example:

if( list != null and !list.isEmpty() ) {
    // do stuff
}

if this feature does not exists this if statement cause exception, but now !list.isEmpty() will never runs when list is null

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top