[Tutor] comparison bug in python (or do I not get it?)

Kent Johnson kent37 at tds.net
Sat Mar 1 16:39:41 CET 2008


Ricardo Aráoz wrote:
>  >>> 1 == True
> True

Yes, True is an integer with value 1. Actually True is a bool but bool 
is a subclass of int:
In [3]: type(True)
Out[3]: <type 'bool'>
In [4]: isinstance(True, int)
Out[4]: True
In [5]: int(True)
Out[5]: 1


>  >>> 5 == True
> False

Right, because 5 != 1

> and yet
> 
>  >>> if 5 : print 'True'
> True
> 
> 
> I thought a non-zero or non-empty was evaluated as True.

Yes, in a boolean context 5 is evaluated as True:
In [7]: bool(5)
Out[7]: True

 From the docs:
In the context of Boolean operations, and also when expressions are used 
by control flow statements, the following values are interpreted as 
false: False, None, numeric zero of all types, and empty strings and 
containers (including strings, tuples, lists, dictionaries, sets and 
frozensets). All other values are interpreted as true.
http://docs.python.org/ref/Booleans.html#Booleans

  Now in the 5 ==
> True line I'm not saying "5 is True", shouldn't it evaluate just like 
> the "if" statement?

No. When you say
   if 5:
you are implicitly converting 5 to a boolean and the 'non-zero evaluates 
to True' rule applies. When you say
   if 5 == True:
you are explicitly comparing the two values and 5 is not converted to 
boolean.

 From the docs:
The operators <, >, ==, >=, <=, and != compare the values of two 
objects. The objects need not have the same type. If both are numbers, 
they are converted to a common type.
http://docs.python.org/ref/comparisons.html


The first one is equivalent to
   if bool(5):
while the second one is
   if 5 == int(True):

Kent


More information about the Tutor mailing list