Reputation: 1793
I have some code here:
m = None
n = None
if not m:
print "Something happens"
>>> Something happens
if I do:
if not m and n:
print "Something happens"
Nothing happens.
But I can do:
m, n = 1,2
if m and n:
print "Something happens"
>>> Something happens
Why are if and if not handled the same way? Does 'if not', not take 'and' statements?
Thank you
Upvotes: 7
Views: 37237
Reputation: 18870
I think you are looking for this article: Truth Value Testing
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
- None
- False
- zero of any numeric type, for example,
0
,0L
,0.0
,0j
.- any empty sequence, for example,
''
,()
,[]
.- any empty mapping, for example,
{}
.- instances of user-defined classes, if the class defines a
__nonzero__()
or__len__()
method, when that method returns the integer zero or bool value False.All other values are considered true — so objects of many types are always true. Operations and built-in functions that have a Boolean result always return
0
orFalse
for false and1
orTrue
for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)
Especially the next chapter explains your case (Boolean Operations — and
, or
, not
):
not has a lower priority than non-Boolean operators
Upvotes: 7
Reputation: 118771
You have an operator precedence problem.
if not m and n
is equivalent to if (not m) and n
. What you want is if not m and not n
or if not (m or n)
.
See also: De Morgan's Laws
Upvotes: 16
Reputation: 1697
not
applied to its closet operand. You wrote if not m and n
where not
applies to m
which is True
, and because of and
, n
is evaluate to False
, hence the entire statement is evaluated to False
.
Upvotes: 2