Emulate a do-while loop in Python?

后端 未结 16 1150
伪装坚强ぢ
伪装坚强ぢ 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:37

    I am not sure what you are trying to do. You can implement a do-while loop like this:

    while True:
      stuff()
      if fail_condition:
        break
    

    Or:

    stuff()
    while not fail_condition:
      stuff()
    

    What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:

    for i in l:
      print i
    print "done"
    

    Update:

    So do you have a list of lines? And you want to keep iterating through it? How about:

    for s in l: 
      while True: 
        stuff() 
        # use a "break" instead of s = i.next()
    

    Does that seem like something close to what you would want? With your code example, it would be:

    for s in some_list:
      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] )
            break # get next s
          else:
            state = STATE_CODE
            # re-evaluate same line
            # continues automatically
    

提交回复
热议问题