do-while loop in Python?
Posted
by Eye of Hell
on Stack Overflow
See other posts from Stack Overflow
or by Eye of Hell
Published on 2009-04-13T06:18:42Z
Indexed on
2010/03/14
0:15 UTC
Read the original article
Hit count: 620
python
|while-loops
I need to emulate a do-while loop in a python. But, unfortunately, following straightforward code does not work:
l = [ 1, 2, 3 ]
i = l.__iter__()
s = None
while True :
if s :
print s
try :
s = i.next()
except StopIteration :
break
print "done"
Instead of "1,2,3,done" I have the following output:
[stdout:]1
[stdout:]2
[stdout:]3
None['Traceback (most recent call last):
', ' File "test_python.py", line 8, in <module>
s = i.next()
', 'StopIteration
']
What can I do in order to catch 'stop iteration' excepton and break a while loop properly?
Example why such thing may be needed. State machine:
s = ""
while True :
if state is STATE_CODE :
if "//" in s :
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT :
if "//" in s :
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
else
state = STATE_CODE
# re-evaluate same line
continue
try :
s = i.next()
except StopIteration :
break
© Stack Overflow or respective owner