Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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 = list_of_ints.__iter__() 

element = None 

while True: 

if element: 

print element 

try: 

element = iterator.next() 

except StopIteration: 

break print "done"

Instead of "1,2,3,done", it prints 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 the 'stop iteration' exception and break a while loop properly?

An example of why such a thing may be needed is shown below as pseudocode.

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

1 Answer

0 votes
by (106k points)

You can implement a do-while loop like this:

while True: 

stuff() 

if fail_condition: 

break

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Aug 31, 2019 in R Programming by Ajinkya757 (5.3k points)
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Oct 8, 2019 in Python by Sammy (47.6k points)
+1 vote
2 answers
asked Aug 28, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...