8

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()
1
  • 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(). Commented Sep 13, 2019 at 19:44

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Does that mean it's preferable to write "if simple_condition() and complex_condition():" than the other way around?
@Joseph I think so.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.