-2

if the first condition is false, which means no matter what the second condition is output will be false. So will the second condition get computed ?

if a > b and b > c:
   do something ...
Chris
  • 26,361
  • 5
  • 21
  • 42
  • No, it won't. This is called short-circuit evaluation, and every language I can think of implements it. – Paul M. Feb 04 '22 at 07:11
  • No, it will not, if the first clause of an `and` expression is `False`, the second will not get computed; similarly, if the first clause of an `or` expression is `True`, the second will not get computed. – Grismar Feb 04 '22 at 07:11

1 Answers1

0

Python short-circuits boolean expressions. As soon as the result of the entire expression is known, evaluation stops.

If you're using and and the left-hand expression is False, the entire expression must be False, so the right-hand expression wil not be evaluated.

Similarly for or if the left-hand expression is True, the right-hand expression will not be evaluated.

Consequently, you should be careful about including function calls with side-effects in boolean expressions. They can lead to program behavior that is difficult to predict.

Chris
  • 26,361
  • 5
  • 21
  • 42