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
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.
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.
“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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With