[Tutor] Splitting a string
Alan Gauld
alan.gauld at btinternet.com
Wed Feb 9 02:14:22 CET 2011
"tee chwee liong" <tcl76 at hotmail.com> wrote
###########
c=('01101')
i=-1
try:
while i<len(c):
i=c.index('0',i+1)
print "Lane fail",i
except ValueError:
print "All Lanes PASS"
pass
#############
The first thing is that you never increment i so the
while condition is never going to terminate, so its
probably just as well you get the exception.
The next thing is that you get the exception whenever
index() can't find a zero. So the exception does not
mean *ALL* lanes pass, it means all the lanes from
the last zero pass. You really want the exception
to stop the search. But it won't indicate all pass
unless it happens the first time...
Using your logic it is easier written as a for loop:
s='01101'
found = False
for i,c in enumerate(s):
if c == '0':
print 'Lane fail',i
found = True
if not Found: print 'All lanes PASS'
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list