exit 2 levels of if/else and execute common code
Chris Angelico
rosuav at gmail.com
Mon Feb 11 10:44:44 EST 2019
On Tue, Feb 12, 2019 at 2:27 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?
One common way to do this is to toss a "return" after the cond2 block.
Means this has to be the end of a function, but that's usually not
hard. Or, as Rhodri suggested, refactor xxyy into a function, which
you then call twice.
ChrisA
More information about the Python-list
mailing list