Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 983
Boosted_d16 Avatar asked Nov 06 '15 11:11

Boosted_d16


People also ask

How do you write if not condition in Python?

Example 1: Python if not – Boolean In this example, we will use Python not logical operator in the boolean expression of Python IF. a = False if not a: print('a is false. ') a is false.

What is if not variable in Python?

Python If with not is used to check whether a variable is empty or not. This variable could be Boolean, List, Dictionary, Tuple ,String or set. Let us go through the examples of each. Note - Below code has been tested on Python 3.

How do you check if something is not in Python?

“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.


2 Answers

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.

like image 92
TigerhawkT3 Avatar answered Sep 18 '22 18:09

TigerhawkT3


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.

like image 31
warvariuc Avatar answered Sep 21 '22 18:09

warvariuc