1

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?

baibo
  • 448
  • 4
  • 20
  • What exactly are you trying to do? – Inbar Rose Dec 10 '13 at 10:16
  • Try thinking of it from the "bottom up". "Execute e() if neither a or b or c and d is true" – Burhan Khalid Dec 10 '13 at 10:18
  • You can use [De_Morgan's_laws](http://en.wikipedia.org/wiki/De_Morgan's_laws) to transform your answer to the ones that @Martijn gives – John La Rooy Dec 10 '13 at 10:19
  • @InbarRose looping and skipping over iterations that are unfaourable – baibo Dec 10 '13 at 10:23
  • Simple conditions are better than complex ones, and `continue` is fine too (see e.g. http://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code). Just replace `elif`s with `if`s and you're done. – georg Dec 10 '13 at 10:46

3 Answers3

6

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

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()
thiruvenkadam
  • 4,170
  • 4
  • 27
  • 26
1
if not any((a, b, (c and d))):
    e()
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 1
    This would evaluate `a`, `b` and `c` (and perhaps `d`) before calling `any()`. This will *not* short-circuit when `a` evaluates to a false value. That could be important. – Martijn Pieters Dec 10 '13 at 10:23