Reputation: 113
Following is the code that is yielding confusing results.
a = None
b = 1
print a and b
if a and b is None:
print "True"
else:
print "False"
Here bool(a) is false as it's none. So via short circuit, the expression should return None. This is actually happening. However, during if condition, the condition fails. Although a and b yields None, the condition fails and priting false at the output. Can someone explain why it's happening?
Upvotes: 1
Views: 59
Reputation: 6237
a and b is None
is evaluated the same as a and (b is None)
, so the expression evaluates to None, and execution jumps to the else clause.
If you add brackets (a and b) is None
, then your code will print "True" as you expect.
This is because is
has a higher precedence than and
in Python. Take a look at the operator precedence documentation for more details.
Upvotes: 7