python: if not this and not that

10,456

Solution 1

This is called De Morgan's Law. (not A) and (not B) is equivalent to not (A or B), and (not A) or (not B) is equivalent to not (A and B).

Technically, it's very slightly faster to use the latter, e.g. not (A and B), as the interpreter evaluates fewer logical statements, but it's trivial. Use the logical structure that allows you to state the condition as clearly as possible, on a case-by-case basis.

Solution 2

if not (var1 and var2) is equivalent to if not var1 or not var2 so your conditions are not the same.

Which one is correct depends on your business logic.

Solution 3

The first is what you want. It checks that both variables are False. The second only checks that var1 and var2 is False, which means that they are not both True simultaneously; one could be True and the other False, and the second if would return True.

Solution 4

Your first example is equivalent to

if not any((var1, var2)): ...

and your second is equivalent to

if not all((var1, var2)): ...

Those variants might represent the underlying problem better.

If they do, use those.

Share:
10,456
Boosted_d16
Author by

Boosted_d16

Python and PowerPoints. The 2 most important Ps in the world.

Updated on June 18, 2022

Comments

  • Boosted_d16
    Boosted_d16 almost 2 years

    I want to write a condition which checks if both variables are False but I'm not sure if what I'm using is correct:

    if not var1 and not var2: 
         #do something 
    

    or should it be:

    if not (var1 and var2):
        #do something