7

I am curious if Python will continue checking conditions in an if statement if the first condition returns False. I'm wondering about this because I want to know if best practice is try to check conditions with low time-complexity before more complex checks.

Is there any difference between these two snippets?

if condition_1() and condition_2():
    do_something()

and

if condition_1():
    if condition_2():
        do_something()
Joseph
  • 125
  • 1
  • 4
  • 4
    There is no difference. Python will lazily evaluate the boolean conditions left to right in an `if` statement. If `condition_1()` is `False`, it will not try to evaluate `condition_2()`. – James Sep 13 '19 at 19:44

1 Answers1

2

Yes, python boolean operators do short-circuit

Both code samples are semantically equivalent, but the first is more readable, as it has lower level of nesting.

SergeyA
  • 61,605
  • 5
  • 78
  • 137