exit 2 levels of if/else and execute common code

Irv Kalb Irv at furrypants.com
Mon Feb 11 11:17:20 EST 2019


> On Feb 11, 2019, at 7:25 AM, Neal Becker <ndbecker2 at gmail.com> wrote:
> 
> I have code with structure:
> ```
> if cond1:
>  [some code]
>  if cond2: #where cond2 depends on the above [some code]
>    [ more code]
> 
>  else:
>    [ do xxyy ]
> else:
>  [ do the same xxyy as above ]
> ```
> 
> So what's the best style to handle this?  As coded, it violates DRY.  
> Try/except could be used with a custom exception, but that seems a bit heavy 
> handed.  Suggestions?
> 

I like the additional function approach others have mentioned.  But if you want a different approach, you could do this:

runExtraCode = True    # set some Boolean
if cond1:
    [some code]
    if cond2:
        [more code]
        runExtraCode = False  # both conditions met, no need to run the extra code

if runExtraCode:
    [do xxyy]


Irv



More information about the Python-list mailing list