user3058846
user3058846

Reputation:

Checking multiple conditions and avoiding code duplication in Python

This is a 3-way conditional filtering happening inside a loop. Here n must definitely meet one among the three conditions; it must be zero, negative or a positive number. Function *dothis()* is repeated twice in the code (for zero or negative). Since one requires continuing the loop and another requires to break it, we can't group the conditions either. The third one is filtered last and also needs to break the loop but after executing a different function *dothat()*.

I couldn't find another way, which would be much more elegant, to do this. These function calls, if replaced by a series of statements would make it look even worse (which is happening in my real code). Are there any possible workarounds?

while True:
    if n == 0:
        dothis()
        continue
    if n < 0:
        dothis()
        break
    dothat()
    break

Note: it is essential that all these must be inside the loop.

Upvotes: 0

Views: 455

Answers (4)

flakes
flakes

Reputation: 23624

I personally prefer to separate code into logical sections. If it can only happen once, then only write it once. Although this way isn't as compact/ doesn't look as pretty, I find that it's more obvious what will happen. When I (or someone else) glances at the code I can say.. "Okay it will either dothis() or dothat() then break or continue."

Assuming in this case that n is not changed by dothis() or dothat()

 while True:
    # How to call
    if n <= 0:
        dothis()
    else:
        dothat()
    # How to end
    if n == 0:
        continue
    else:
        break

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56654

It might be better to separate your decision-points: 1) do I do this or that, and 2) do I stop here?

while True:
    if n > 0:
        dothat()
    else:
        dothis()

    if n:
        break

Upvotes: 0

user590028
user590028

Reputation: 11730

You're likely to get alot of stylistic/preference recommendations (and one person who will point out your test for equality is flawed -- you used assignment rather than equality). I think in the long run, it's what ever you feel is simpler to understand.

My personal favorite is:

while n == 0:
    dothis()
if n < 0:
    dothis()
elif n:
    dothat()

Upvotes: 1

Torxed
Torxed

Reputation: 23480

while True:
    if n <= 0:
        dothis()
        if n == 0: continue
    dothat()
    break

Assuming dothis() is actually the same function in both cases. This would produce the same outcome.

Upvotes: 1

Related Questions