In which order is an if statement evaluated in Python

Python's or operator short-circuits and it will be evaluated left to right:

if (foo > 5) or (bar > 6):
    print 'foobar'

If foo > 5, then bar > 6 will not even be tested, as True or <anything> will be True. If foo isn't > 5, then bar > 6 will be tested.


It will be evaluated left to right.

>>> def a():
...     print 'a'
...     return False
... 
>>> def b():
...     print 'b'
...     return False
... 
>>> print a() or b()
a
b
False
>>> def c():
...     print 'c'
...     return True
... 
>>> print c() or a()
c
True

The left clause will be evaluated first, and then the right one only if the first one is False.

This is why you can do stuff like:

if not person or person.name == 'Bob':
    print "You have to select a person and it can't be Bob"

Without it breaking.

Conversely, with an and clause, the right clause will only be evaluated if the first one is True:

if person and person.name:
   # ...

Otherwise an exception would be thrown when person is None.


To expand Blender's explanation a bit further, the or operator has something else built-in:

<expression A> or <expression B>

This will evaluate expression A first; if it evaluates to True then expression A is returned by the operator. So 5 or <something> will return 5 as 5 evaluates to True.

If expression A evaluates to False, expression B is returned. So 0 or 5 will return 5 because 0 evaluates to False.

Of course you can chain this as much as you want:

<expr 1> or <expr 2> or <expr 3> or ... or <expr n>

In general, or will return the first expression which evaluates to True, but keep its original value. If there is no expression that evaluates to True, it will simply return the last expression (which evaluates to False).

The and operator works in a similar but inversed way. It will return the first expression which does evaluate to False, but keep its original value. If there is no expression that evaluates to False, it will simply return the last expression (which will evaluate to True).

As an example, both 0 and 5 and 5 and 0 will return 0 because 0 evaluates to False, but 2 and 3 will return 3 because 3 is the last expression and everything evaluates to True.

In any way (to come back to the question): All expressions are evaluated from left to right, and if a rule from above allows it, further expressions will not be touched.

Tags:

Python