Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's no prepackaged "do-while", but the general Python way to implement peculiar looping constructs is through generators and other iterators, e.g.:</p> <pre><code>import itertools def dowhile(predicate): it = itertools.repeat(None) for _ in it: yield if not predicate(): break </code></pre> <p>so, for example:</p> <pre><code>i=7; j=3 for _ in dowhile(lambda: i&lt;j): print i, j i+=1; j-=1 </code></pre> <p>executes one leg, as desired, even though the predicate's already false at the start.</p> <p>It's normally better to encapsulate more of the looping logic into your generator (or other iterator) -- for example, if you often have cases where one variable increases, one decreases, and you need a do/while loop comparing them, you could code:</p> <pre><code>def incandec(i, j, delta=1): while True: yield i, j if j &lt;= i: break i+=delta; j-=delta </code></pre> <p>which you can use like:</p> <pre><code>for i, j in incandec(i=7, j=3): print i, j </code></pre> <p>It's up to you how much loop-related logic you want to put inside your generator (or other iterator) and how much you want to have outside of it (just like for any other use of a function, class, or other mechanism you can use to refactor code out of your main stream of execution), but, generally speaking, I like to see the generator used in a <code>for</code> loop that has little (ideally none) "loop control logic" (code related to updating state variables for the next loop leg and/or making tests about whether you should be looping again or not).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload