[Tutor] Misc question about scoping

Alan Gauld alan.gauld at btinternet.com
Fri Jun 4 10:08:02 CEST 2010


"Steven D'Aprano" <steve at pearwood.info> wrote

>> isThumbnail = True if size == "thumbnail" else False
>
> That is technically correct, you could do that. That's a good 
> example of
> the syntax of the `if` expression, but it's a bad example of where 
> to
> use it:

In the sense that an equality test will always give a real
boolean value as a result I agree. But in the more generic
case where we use an expressiioon as a boolean it can
be usful. Specifically if the test involves boolean
operators Python does not return True/False but the
values of the operands. In that case using the if/else
form yields a  real boolean result.

eg

flag = True if  (smoeValue or another) else False

is different to

flag = someValue or another

Which was why I thought it worth pointing out that the if/else
could be used.

> with all due respect to Alan who suggested it. It really is an
> unnecessarily complicated and verbose way of doing a
> simple assignment,

In the case of an equality test I agree.

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




More information about the Tutor mailing list