[Tutor] using 'and ' and 'or' with integers
Brian van den Broek
brian.van.den.broek at gmail.com
Wed Jan 9 08:49:07 CET 2013
On 9 January 2013 01:56, ken brockman <krush1954 at yahoo.com> wrote:
> I was looking through some lab material from a computer course offered at UC
> Berkeley and came across some examples in the form of questions on a test
> about python.
> 1 and 2 and 3
> answer 3
> I've goggled it till i was red in the fingers, but to no avail.. Could
> someone be kind enuff to direct me to some docs that explain this?? I've no
> clue what the hell is going on here..
> Thanks much for any help you may supply.
>
Ken,
I don't have a link, but I'll take a stab.
Any non-zero integer evaluates to True:
>>> if 42: print "!"
!
Python's boolean operators use short-circuit evaluation---they return
a value as soon as they have seen enough to know what truth-value the
compound evaluates to. And, the value they return isn't always True or
False. Rather, they return the object in virtue of which they had seen
enough to know whether the evaluated value is True or False:
>>> True or 4
True
>>> 4 or True
4
Since 4 evaluates as True, and `something True or anything at all'
will evaluate to True, in the second case 4 is returned.
Likewise, in your case:
>>> 1 and 2 and 3
3
>>> (1 and 2) and 3
3
>>> 1 and (2 and 3)
3
>>>
(I put the two bracketting ones in as I cannot recall if python
associates to the left or to the right. I'm pretty sure left, but it
doesn't matter here.) Consider the last version. Since 1 evals as
True, python has to look at the left conjunct. 2 does, too, so it has
to look at 3. Since 3 does, and python now knows the whole evals as
True, it returns 3.
HTH,
Brian vdB
More information about the Tutor
mailing list