need clarification on -0

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Nov 28 04:18:17 EST 2009


On Fri, 27 Nov 2009 23:09:06 -0800, moijes12 wrote:

> Hi
> 
> I know the value -0 is quite meaningless and makes little sense.

Actually, when it comes to floating point values, it is very useful to be 
able to distinguish between -0 and +0.


> But I
> was just fiddling.I am unable to figure out the below result
> 
> 
>>>> -0 and True
> 0 ----------> (Why is this 0 and not say True or False)

You need to know two things about Python:

(1) All values can be interpreted in a boolean context:

if None:
    print "this will never be printed"
else:
    print "this is always printed"

False values include: None, 0, 0.0, "", [], {} and of course False.

True values include nearly everything else.


(2) `and` and `or` are short-cut operators. They return the first 
argument which unambiguously defines the result:

X and Y => X if X is a false value, and Y if X is a true value.
X or Y => X if X is a true value, and Y if X is a false value.


Why do `and` and `or` return objects other than True and False? This is 
especially useful when using `or` in situations like this:

process(main_list or fallback_list)

which will process the first list of the two which is not empty.


-- 
Steven



More information about the Python-list mailing list