Try/except vs. if/else

Batista, Facundo FBatista at uniFON.com.ar
Tue Sep 23 11:40:38 EDT 2003


#- In my understanding, using try/except rather than if/else is more 
#- pythonic. However, sometimes it is difficult to use the later.

It's more pythonic to use always the right tool for the problem.


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

IMHO, better the case 2. One detail, stop the iteration when you have an ok
(code untested):

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


.	Facundo





More information about the Python-list mailing list