Learing Python, Newbie question

Steve Holden sholden at holdenweb.com
Thu Oct 25 16:25:45 EDT 2001


"Terry Reedy" <tjreedy at home.com> wrote ...
>
> "Johannes Gamperl" <info at devshare.de> wrote in message
> news:MPG.1642065dc9ef9d80989687 at news.t-online.de...
> > thx a lot .. this works fine. Do you know if there is a
> > coditional operator in python ( ?: )
>
> > if os.path.exists("gbook.txt"):
> >   db_first = 0;
> > else:
> >   db_first = 1;
>
Oh, dear. Setting a Boolean depending on the value of a Boolean ...

> As others have pointed out,
> a)your particular example does not need a conditional expression, and
> b) there has been discussion and controversy on adding a 'true' c.e to
> python.
> In the meanwhile -- to answer your question -- you can almost always
> do something like the following:
>
> db_first = not os.path.exists("gbook.txt") and 1 or 0 #good (at least
> ok)
>
Oh dear.

> But note that
>
> *BAD* db_first = os.path.exists("gbook.txt") and 0 or 1 *BAD*
>
> would always assign db_first to 1 and never 0.  If you understand why
> the good example works and are sure that you will never make the
> mistake exemplified in the *BAD* example, you have my permission to
> use this idiom ;-)  (But be aware that some hate it).
>
Erm, what's wrong with:

    db_first = not os.path.exists("gbook.txt") # best?

just as a matter of interest? "not" *always* returns 0 (when its operand
evaluates true) or 1 (when its operand evaluates false).

more-succinctly-than-usual-ly y'rs  - steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list