A C-like if statement

Kay Schluehr kay.schluehr at gmx.net
Fri Feb 24 14:30:12 EST 2006


Roy Smith wrote:
> Bob Greschke <bob at passcal.nmt.edu> wrote:
> >I miss being able to do something like this in Python
> >
> >1f (I = a.find("3")) != -1:
> >    print "It's here: ", I
> >else:
> >    print "No 3's here"
> >
> >where I gets assigned the index returned by find() AND the if statement gets
> >to do its job in the same line.  Then you don't have to have another like
> >that specifically gets the index of the "3".  Is there a way to do this in
> >Python?
>
> It is a deliberate and fundamental design decision in Python that
> assignment is a statement, not an expression with side effects.  This
> means you often need an "extra" line compared to a classic C "assign
> and test" idiom such as you have above.  I, like you, often miss the
> compactness of the C idiom, but there it is.

Hmm. A statement has side-effects but it returns no value. And yes, you
can create a name within an expression producing a value in Python,
using a list/generator comprehension. The solution to Bob's problem
would look like this:

if (I for I in (a.find("3"),) ) != -1:
     print "It's here: ", I
else:
     print "No 3's here"


Kay




More information about the Python-list mailing list