A C-like if statement

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Feb 23 17:14:53 EST 2006


On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote:

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

There are *reasons* why Python discourages functions with side-effects.
Side-effects make your code hard to test and harder to debug.

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

Then write a function! Instead of calling the try..except block in every
branch directly, pull it out into a function:

def test(s,what):
    try:
        i = s.index(what)
        print "It's here: ", i
    except ValueError:
        print "No 3's here"


-- 
Steven.




More information about the Python-list mailing list