Try/except vs. if/else

Bob Gailer bgailer at alum.rpi.edu
Wed Sep 24 10:33:58 EDT 2003


At 09:10 AM 9/23/2003, Shu-Hsien Sheu wrote:

>Hi,
>
>In my understanding, using try/except rather than if/else is more pythonic.

If/else and try/except are both Pythonic. In many cases you don't even get 
to choose.

>However, sometimes it is difficult to use the later.
>For example, I want to search for a sub string in a list composed of 
>strings. It is considered "possitive" if there is a match, no matter how many.
>
>my_test = ['something', 'others', 'still others']
>
>case 1: try/except
>
>hit = 0
>for i in my_test:
>    try:
>       i.index('some')
>       hit = 1
>    except ValueError:
>       pass
>
>
>
>case 2: if/else
>
>hit = 0
>for i in my_test:
>    if 'some' in i:
>       hit = 1

Consider breaking out of the loop at the first success

for i in my_test:
    if 'some' in i:
       hit = 1
       break
else:
   hit = 0

Iist comprehension can also be an alternative:

hit = [i for i in my_test if 'some' in i]

>It seems to me that in a simple searching/matching, using if might be 
>better and the code is smaller. Try/except would have its strengh on 
>catching multiple errorrs. However, problems occur if the criteria is 
>composed of "or" rather than "and". For instance:
>
>if (a in b) or (c in b):
>    *do something
>
>try:
>    b.index(a)
>    b.index(c)
>    *do something
>except ValueError:
>   pass
>
>The above two are very  different.
>
>Am I right here?

AFAIAC its a mater of style.

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003


More information about the Python-list mailing list