Truthiness

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Thu Oct 23 11:01:43 EDT 2014


On 10/23/2014 04:47 PM, Alain Ketterlin wrote:
> Simon Kennedy <sffjunkie at gmail.com> writes:
>
>> Just out of academic interest, is there somewhere in the Python docs where the following is explained?
>>
>>>>> 3 == True
>> False
>>>>> if 3:
>> 	print("It's Twue")
>> 	
>> It's Twue
>>
>> i.e. in the if statement 3 is True but not in the first
>
> https://docs.python.org/2/reference/compound_stmts.html#the-if-statement
>
> says: "The if statement [...] selects exactly one of the suites by
> evaluating the expressions one by one until one is found to be true (see
> section Boolean operations for the definition of true and false)"
>

Exactly, but in

if 3 == True:

the expression is 3==True , in which 3 and True compare unequal, thus, 
the expression is false.
On the other hand, in

if 3:

the expression to evaluate is just the int object and the rules below apply.

> and then:
>
> https://docs.python.org/2/reference/expressions.html#booleans
>
> says: "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."
>
> (links are to the 2.7 version of the reference manual, I think not much
> has changed in 3.* versions.)
>
> -- Alain.
>




More information about the Python-list mailing list