True of False
Gary Herron
gherron at islandtraining.com
Thu Sep 27 13:38:39 EDT 2007
Richard Thomas wrote:
> On 27/09/2007, Casey <Caseyweb at gmail.com> wrote:
>
>> On Sep 27, 12:48 pm, "Simon Brunning" <si... at brunningonline.net>
>> wrote:
>>
>>> On 9/27/07, kou... at hotmail.com <kou... at hotmail.com> wrote:
>>>
>>>
>>>> I tried writing a true and false If statement and didn't get
>>>> anything? I read some previous posts, but I must be missing
>>>> something. I just tried something easy:
>>>>
>>>> a = ["a", "b", "c", "d", "e", "f"]
>>>>
>>>> if "c" in a == True:
>>>> Print "Yes"
>>>>
>>>> When I run this, it runs, but nothing prints. What am I doing wrong?
>>>>
>>> Just use
>>>
>>> if "c" in a:
>>>
>>> and all will be well. The True object isn't the only truthy value in
>>> Python - see <http://docs.python.org/lib/truth.html>.
>>>
>> I would recommend the OP try this:
>>
>> run the (I)python shell and try the following:
>>
>>
>>>>> a = [x for x in "abcdefg"]
>>>>> a
>>>>>
>> ['a','b','c','d','e','f','g']
>>
>>>>> "c" in a
>>>>>
>> True
>>
>>>>> "c" in a == True
>>>>>
>> False
>>
>>>>> ("c" in a) == True
>>>>>
>> True
>>
>> The reason your conditional failed is that it was interpreted as "c"
>> in (a == True) which is False.
>> the "==" operator binds at a higher precedence level than the "in"
>> operator, just as multiplication
>> binds higher than addition
>>
>>
>
> Actually it evaluates '("c" in a) and (a == True)'. You can check like so:
>
> import dis
> a = list("abcdef")
> dis.dis(lambda: "c" in a == True)
>
> And just follow the bytecode operations.
>
Yikes. So I did that and you're correct. I've always looked at
chained comparisons with mild suspicion. Now I guess that suspicion is
justified. Interpreting
a<b<c
as
a<b and b<c
make perfect sense to me, but interpreting
"c" in a == True
as
("c" in a) and (a == True)
is not at all natural.
Gary Herron
> -- Richard.
>
>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
More information about the Python-list
mailing list