Re: Some python comments/questions [ #1: "?:" equivalent ]

Guido.van.Rossum@cwi.nl
Tue, 12 Oct 1993 14:45:56 +0100

> >>> ((( 1 < 2 ) and ( 'Less Than' ) or ( 'Not Less Than' )))
> 'Less Than'
> >>> ((( 3 < 2 ) and ( 'Less Than' ) or ( 'Not Less Than' )))
> 'Not Less Than'

BUT, if you use this with generalized expressions instead of literals,
it may fail: if you evaluate "x and y or z" with x true and y false
(e.g. an empty list), result will still be z, unlike for x?y:z, where
it will be y.

> >>> ( 'Not Less Than', 'Less Than' )[ ( 1 < 2 ) ]
> 'Less Than'
> >>> ( 'Not Less Than', 'Less Than' )[ ( 3 < 2 ) ]
> 'Not Less Than'

This of course has the disadvantage that it always evaluates both
branches of the if-then-else.

> BUT: since None and empty sequences are also
> false and all others true, there is no guarantee that this
> will work for all tests.

To convert any Boolean x into 0 or 1: "x and 1 or 0".

Anybody come up with a reasonable alternative syntax for x?y:z...?

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>

PS sometimes I get mail suggesting a switch/case statement. Do people
generally miss this?