9
if cpu_expensive_condition() or simple_condition():
        do_something()

out of two condition in OR statement in above python code which will be evaluate first ? , and is it compulsory that both will be evaluate ?

iamgopal
  • 8,806
  • 6
  • 38
  • 52

4 Answers4

22

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.

Quoted from Python Language Reference

SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
5

Python evaluates from left to right, and both sides do not need to be evaluated. Consider the following example.

def left(x):
    print 'left'
    return x

def right(x):
    print 'right'
    return x

if left(False) or right(False):
    print 'Done'

if left(True) or right(True):
    print 'Done'

This will produce the following output:

left
right #This is where the first if statement ends.
left
Done  #Only the left side was evaluated
4

According to Boolean Operations — and, or, not in the Python documentation:

This is a short-circuit operator, so it only evaluates the second argument if the first one is False.

So cpu_expensive_condition() will always be evaluated. simple_condition() will only be evaluated when cpu_expensive_condition() returns False (or something that evaluates to False, such as 0 or '' or None).

See also: Does Python support short-circuiting?

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
1

Python does short-circuit evaluation. Of course the first statement will be evaluated first. The second will only be evaluated if the first is False or false-ish.

kojiro
  • 74,557
  • 19
  • 143
  • 201