简体   繁体   中英

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

 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?

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

You elif s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM