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:

  • python runs the all 3 if one by one, and one of them is wrong, the test fails
  • or python runs if one by one, at the first failed if, the test fails and the others if are not run

How does python run this test internally?

Thank you and regards, Hugo

Foi útil?

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."

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top