[Tutor] Boolean operations
Kent Johnson
kent37 at tds.net
Wed Sep 2 18:45:17 CEST 2009
On Wed, Sep 2, 2009 at 6:30 AM, Anthony Casey<AMCasey at xtra.co.nz> wrote:
> Hello, tutors.
>
> I'm someone who used to programme as a hobby and who is trying to get back
> into it via Python. I'm reading Programming in Python 3 by Summerfield
> (excellent book).
>
> I read something unusual about Boolean operations in Python:
>
>>>> five = 5
>>>> two = 2
>>>> zero = 0
>>>> five and two
> 2
>
> I understand what it's doing here: returning the operand. But what is the
> practical application of that? How might I use that function? (Short-sighted
> imagination, I realise.)
The equivalent behaviour for 'or' can be used to provide a default, for example:
value = may_be_empty or 3
The obsolete (and problematic) hack for a ternary expression uses this:
x = (cond and true_value) or false_value
If cond evaluates to True, x will have true_value, otherwise it will
have false_value.
Kent
More information about the Tutor
mailing list