Try/except vs. if/else
Gerrit Holl
gerrit at nl.linux.org
Tue Sep 23 11:45:36 EDT 2003
Shu-Hsien Sheu wrote:
> In my understanding, using try/except rather than if/else is more
> pythonic. 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
Much faster would be:
def check():
for elem in my_test:
if 'some' in elem:
return True
...this way, it immediatly stops checking all following values once it finds
a single match.
> 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.
Agreed.
> 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.
It would be more similar to use 'if (a in b) and (c in b)',
because that is what the try/except block does. If so, I
think it has the same effect.
I would absolutely prefer the former, because I don't like function
calls who neither change an object whose return value is
thrown away.
regards,
Gerrit.
--
243. As rent of herd cattle he shall pay three gur of corn to the
owner.
-- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
http://www.sp.nl/
More information about the Python-list
mailing list