[Tutor] Boolean operations

Alan Gauld alan.gauld at btinternet.com
Wed Sep 2 22:07:34 CEST 2009


"Anthony Casey" <AMCasey at xtra.co.nz> wrote

>>>> 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?

Try

>>> bool(2)
True
>>> bool(0)
False

So you can use the retuirn from the and as a boolean value in a test 
condition:

if 5 and 2:
    print 'its true')

if 5 and 0:
     print 'its not'

> (I know how binary Booleans work etc., so this is a bit of a change of
> outlook.)

Hopefully that clears it up.
There are some klunky hacks that you can do based on this side-effect
but there are usually cleaner solutions  especially since Pyton 2.5
introduced a ternary operator


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list