Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python:can I assume that conditions are tested from left to right and stop when met?

I will use the followig code as reference for my question:

>>> a = 10
>>> if a or b:
...     print(a)
...
10
>>> if False and b:
...     print(a)
...
>>> if a and b:
...     print(a)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

I will conditionally test cases where:

  • a is defined and b may or may not be defined
  • a is False and b is not defined, or a is True and b is defined

I would use if a or b: for the first case and if a and b: for the second one. Per my tests above it works, but this assumes that i) the parsing of the condition is from left to right and ii) it stops when the condition status is known

Is this a documented behavior of Python and are these correct assumptions?

like image 539
WoJ Avatar asked Nov 19 '13 14:11

WoJ


2 Answers

Yes.

It's in the doc so it's true.

http://docs.python.org/2/library/stdtypes.html#boolean-operations-and-or-not

like image 172
Rudy Bunel Avatar answered Sep 28 '22 14:09

Rudy Bunel


Short answer: Yes!

All conditions are evaluated left to right.

And in most cases it will short circuit whenever a "True" condition is met, depending on what you are looking for.

For instance, in the case of AND both sides must be evaluated as True. But in the case of OR If the first side is true, it will short-circuit.

For more information about AND and OR in Python, check out The Peculiar Nature of AND and OR

like image 34
Inbar Rose Avatar answered Sep 28 '22 16:09

Inbar Rose