简体   繁体   中英

python: if not this and not that

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

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, eg 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.

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.

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 .

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.

You should use the first example, it's more Pythonic.

Also, your second example is flawed. It will fail if 1 of your variables are True, and the other False.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM