I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:
list_of_ints = [ 1, 2, 3 ]
iterator =
My code below might be a useful implementation, highlighting the main difference between do-while vs while as I understand it.
So in this one case, you always go through the loop at least once.
first_pass = True
while first_pass or condition:
first_pass = False
do_stuff()
Why don't you just do
for s in l :
print s
print "done"
?
See if this helps :
Set a flag inside the exception handler and check it before working on the s.
flagBreak = false;
while True :
if flagBreak : break
if s :
print s
try :
s = i.next()
except StopIteration :
flagBreak = true
print "done"
Exception will break the loop, so you might as well handle it outside the loop.
try:
while True:
if s:
print s
s = i.next()
except StopIteration:
pass
I guess that the problem with your code is that behaviour of break
inside except
is not defined. Generally break
goes only one level up, so e.g. break
inside try
goes directly to finally
(if it exists) an out of the try
, but not out of the loop.
Related PEP: http://www.python.org/dev/peps/pep-3136
Related question: Breaking out of nested loops
while condition is True:
stuff()
else:
stuff()
Python 3.8 has the answer.
It's called assignment expressions. from the documentation:
# Loop over fixed length blocks
while (block := f.read(256)) != '':
process(block)