Learing Python, Newbie question

Terry Reedy tjreedy at home.com
Thu Oct 25 13:26:57 EDT 2001


"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;

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)

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).

Terry J. Reedy






More information about the Python-list mailing list