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 defineda
is False and b
is not defined, or a
is True
and b
is definedI 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?
Yes.
It's in the doc so it's true.
http://docs.python.org/2/library/stdtypes.html#boolean-operations-and-or-not
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With