[Tutor] comparison bug in python (or do I not get it?)
kent37 at tds.net
Sat Mar 1 16:39:41 CET 2008
Ricardo Aráoz wrote:
> >>> 1 == True
Yes, True is an integer with value 1. Actually True is a bool but bool
is a subclass of int:
In : type(True)
Out: <type 'bool'>
In : isinstance(True, int)
In : int(True)
> >>> 5 == True
Right, because 5 != 1
> and yet
> >>> if 5 : print 'True'
> I thought a non-zero or non-empty was evaluated as True.
Yes, in a boolean context 5 is evaluated as True:
In : bool(5)
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.
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
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
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.
The first one is equivalent to
while the second one is
if 5 == int(True):
More information about the Tutor