and
is a short-circuit operator.
The second argument is evaluated if the first one is True
. Similarly, for the subsequent arguments.
Pergunta
Could you please advise how python runs several terms if?
For example:
a = 0
b = 0
c = 0
if a == 0 and b == 1 and c == 0:
# test fails
I guess python internally splits the test into 3 if. But then, there are 2 possible cases:
How does python run this test internally?
Thank you and regards, Hugo
Solução
and
is a short-circuit operator.
The second argument is evaluated if the first one is True
. Similarly, for the subsequent arguments.
Outras dicas
This doesn't have anything to do with the conditional clause, but the boolean operators and
and or
. They are short-circuit operators. If the first value is False, then False is immediately used. Otherwise, the second value is evaluated.
Here's a nice example:
>>> def a():
... print 'a is running!'
... return True
...
>>> def b():
... print 'b is running!'
... return False
...
>>> def c():
... print 'c is running!'
... return True
...
>>> if a() and b() and c():
... print 'hello!'
...
a is running!
b is running!
Because b
returns False
, c
does not end up running because there is no need.
The second. and
/or
are short-circuit operators - if there is no need, the second argument is not evaluated. See the doc boolean-operations-and-or-not.
Python uses "lazy evaluation" for if
:
See the docs
"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."