A C-like if statement

Bob Greschke bob at passcal.nmt.edu
Thu Feb 23 14:04:38 EST 2006


"Roy Smith" <roy at panix.com> wrote in message 
news:dtl04p$5q2$1 at reader2.panix.com...
> 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.
>
> It's also unpythonic to return magic values to indicate failure.
> Throwing an exception would be the more normal way of doing it.  So,
> I'd expect the above to translate into something like:
>
> try:
>    i = a.find("3")
>    print "It's here: ", i
> except NotFound:
>    print "No 3's here"

Nuts.  I guess you're right.  It wouldn't be proper.  Things are added or 
proposed every day for Python that I can't even pronounce, but a simple 'if 
(I = a.find("3")) != -1' isn't allowed.  Huh.  It might be time to go back 
to BASIC. :)

I think your way would work if .find() were replaced with .index().  I'm 
just trying to clean up an if/elif tree a bit, so using try would make 
things bigger.

Thanks!

Bob





More information about the Python-list mailing list