1

What is the best way to implement the following code without having the same code duplicated in two different blocks, but while maintaining efficiency and readability?

if (expression1):
    if (expression2 that can only be checked if expression1):
        doSomething()
    else:
        doSomethingElse()
else:
    doSomethingElse()
Robert Harvey
  • 200,592

2 Answers2

5
if( expression1 and expression2):
 doSomething()
else:
 doSomethingElse()

Since Python supports short-circuit evaluation, Expression2 will only be evaluated if expression1 is true.

DMS
  • 74
  • 2
1

I like the AND answer, but you could also use early return.

if exp1 :
    if exp2 :
        doSomething()
        return

doSomethingElse()
Ewan
  • 83,178