[Tutor] What is the difference between checking false?

Dave Angel davea at davea.name
Sun Jun 16 04:03:24 CEST 2013


On 06/15/2013 09:30 PM, Jim Mooney wrote:
> ##This is puzzling me. If I check the equality of 0, None, empty
> string, and empty list with False,
> ##only zero satisfies the equality. But if I use them in a not
> statement, they all turn out False.
> ##What gives?
>
> #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs
>
> print('Zero is equal to False' if 0 == False else 'Zero is NOT equal to False')
> print('None is equal to false' if None == False else 'None is NOT
> equal to false')
> print('Empty string is equal to False' if '' == False else 'Empty
> string is NOT equal to False')
> print('Empty list is equal to false' if [] == False else 'Empty list
> is NOT equal to false')
> print()
> print('Zero is equal to False' if not 0 else 'Zero is NOT equal to False')
> print('None is equal to false' if not None else 'None is NOT equal to false')
> print('Empty string is equal to False' if not '' else 'Empty string is
> NOT equal to False')
> print('Empty list is equal to False' if not [] else 'Empty list is NOT
> equal to false')
>
> ##Results:
> ##
> ##Zero is equal to False
> ##None is NOT equal to false
> ##Empty string is NOT equal to False
> ##Empty list is NOT equal to false
> ##
> ##Zero is equal to False
> ##None is equal to false
> ##Empty string is equal to False
> ##Empty list is equal to False
>

Why such a convoluted way of expressing yourself?  Especially the second 
half when the statements are clearly different than what you're testing.

False is equivalent to the int 0 for historical reasons, back before 
there was a separate boolean type.  Likewise True is equivalent to the 
int 1.  You shouldn't write any code that counts on it, however.

You don't say which of the remaining ones in the first group are 
surprising.  False is not the same as any other type except the special 
one I already mentioned.


As for the second group, applying the not operator will produce exactly 
True or False, the same way that applying bool() will.  The only 
difference is that if one would produce True, the other will produce 
False.  That's what 'not' means.  But it's certainly not doing a value 
comparison like your literal claims.  If the item is truthy, not 
produces False.  And if the item is falsey, not produces True.



-- 
DaveA


More information about the Tutor mailing list