Yes, because Python and is short-circuited (wikipedia) and evaluated from left to right.
That means if x == None
, it won't evaluate the rest: Python already knows that the evaluation of the full and
is going to be False
, because:
False and True and True and True
is still False
Consider the following:
x = None
if x is not None and a != "test":
print "Point 1"
else:
print "Point 2"
The variable a
is not initialized anywhere, right? If Python hits that point, you'll get a Name Error
exception, but what you get is:
Point 2
Meaning that Python doesn't even bother evaluating the a != "test"
part.
Something similar happens with or
. If any condition is True
, Python stops evaluating:
The following code:
x = None
if x is None or a != "test":
print "Point 1"
else:
print "Point 2"
Doesn't throw an exception either, but outputs
Point 1
Bonus:
When checking if a variable is None, is much more recommended using is
(or is not
) rather than ==
or !=
(as explained in the SO question What is the difference between " is None " and " ==None ")