Emulate a do-while loop in Python?

后端 未结 16 874
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:47

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 =         


        
相关标签:
16条回答
  • 2020-11-22 07:19

    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()
    
    0 讨论(0)
  • 2020-11-22 07:19

    Why don't you just do

    for s in l :
        print s
    print "done"
    

    ?

    0 讨论(0)
  • 2020-11-22 07:20

    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"
    
    0 讨论(0)
  • 2020-11-22 07:21

    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

    0 讨论(0)
  • 2020-11-22 07:22
    while condition is True: 
      stuff()
    else:
      stuff()
    
    0 讨论(0)
  • 2020-11-22 07:24

    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)
    
    0 讨论(0)
提交回复
热议问题