a = None
b = 'Test'
if a is None or b is None:
print('Test')
this version is obviously working but:
if (a or b) is None:
print('Test')
Expected would be the same result but it evaluates to False, why?
a = None
b = 'Test'
if a is None or b is None:
print('Test')
this version is obviously working but:
if (a or b) is None:
print('Test')
Expected would be the same result but it evaluates to False, why?
In Python, an or
statement does not just return True
or False
, it returns the first of it's arguments that is "truthy".
In your code, the following happens when evaluating (a or b) is None
:
None
is falsy, and a
is None
, so a or b
returns b
.b
is not None
.(a or b) is None
resolves to False
.Operator precedence and evaluation rules of boolean expressions work a bit different in Python. This is not doing what you imagine:
(a or b) is None
The above condition is asking whether the result of evaluating (a or b)
is None
, and it will never be None
with the current values of a
and b
; a or b
will return 'Test'
(the value of b
), because a
is None
. If you want to test if either one of two values is None
, only the first syntax is valid:
a is None or b is None
Just to be clear, in Python x or y
will return the value of the first non-false expression, and None
, []
, {}
, ''
, 0
and False
are considered false. If what you want is to shorten the expression a bit, this is equivalent to the first version of your code:
if not a or not b:
If you want to be super brief, you can used the following construction:
if None in (a, b):
print('Test')
Please note that while this will work in the majority of cases, the expression is not exactly equivalent to a is None or b is None
but rather a == None or b == None
. See explanation of why this is not the same thing.