Replacing nested 'if' statements with (seemingly) equivalent 'elif' combined with 'not'

Viewed 42
 if statement1:
    if statement2:
       if statement3:
          return desired_action
       else:
          return action3
    else:
      return action2
 else:
   return action1

vs: 2.

 if not statement1:
     return action1
 elif not statement2:
     return action2
 elif not statement3:
     return action3
 else:
     return desired_action

I tend to prefer the second way, but for some reason it seems somewhat.. risky? or unreliable as much as the first method.

Also, do I really need that elif? I return when I reach a certain if. Thank you.

Is there a convention or a standard?

1 Answers

This is equivalent according to De Morgan's laws: NOT (A AND B) = (NOT A) OR (NOT B).

You elifs are required if you want to perform only an single alternative action. Without them (let's say all conditions are False), you would trigger every single alternative action.

Regarding which one of the two codes to chose is a bit subjective. The second one is more appealing and I would tend to go with this one.

NB. your indentation of the second block was incorrect, I fixed it

Related