Logical equivalence of a sequence of if else if else clauses

489 views Asked by At

I am seriously under-slept and I need help in rewriting this small Python piece of logic

for _ in range(100):
    if a:
        continue
    elif b:
        continue
    elif c and d:
        continue
    else:
        e()

I want to have something like

if (some_exprt of a,b,c,d):
    e()

What I got is:

if not a and  not b and (not c or not d):
   e()

but I really can't tell if this is correct or not, am I right?

3

There are 3 answers

0
Martijn Pieters On BEST ANSWER

Start with under what conditions the else branch would not match. It'd be one of a, or b, or c and d, so you would need to use or and not here to express when the else branch of your original code would be picked:

if not (a or b or (c and d)):
    e()

You could then bring the not into the parenthesis by applying one of De Morgan's laws, expressing the preceding test more verbosely as:

if not a and not b and not (c and d):
    e()

which could then be further expanded to:

if not a and not b and (not c or not d):
    e()

which is what you yourself already expanded to. But I'd find the first version to be more readable.

5
thiruvenkadam On

continue cannot work inside an if statement. So I assume you are running this inside a loop(while or for). Try this:

#whatever loop
if not(a or b or (c and d)):
    e()

Second approach without a not will be:

if a or b or (c and d):
    continue
else:
    e()

As M. Martjin Peters explained in the comments, the else block within the second approach is not necessary. You can remove the else and move e() outside the if block. However, in my opinion, an else after an if will make the code more readable.

Second approach can also be written as:

if a or b or (c and d):
    continue
e()
1
John La Rooy On
if not any((a, b, (c and d))):
    e()