7.10) Repeating Actions With The 'While' Loop
If you want to repeat a task several times in a program, you can do this with loops. The while loop will repeat a set of actions until a test is no longer True. Here’s the syntax:
while <Test>: <statement>
For example:
counter=3 print 'Let’s square some numbers' print '(start of loop)' while (counter <= 6): print counter, 'squared is', counter**2 counter+=1 # equivalent to counter=counter+1 print '(end of the loop)'
Notice the colon (:) and the indentation (usually four spaces) which indicates the group of statements to be repeated. The typical way to use this loop is to have a counter that is changed within the loop (here it increases by 1).
Visualise this loop in action with the pythontutor.com visualisation tool.
[advanced_iframe securitykey="cdcd195854f0661ec0561aa6e33a487eadfbcbcc" src="http://pythontutor.com/iframe-embed.html#code=counter%3D3%0Aprint+%22start+of+loop%22%0Awhile+(counter+%3C%3D+6)%3A%0A++++print+counter,+counter**2%0A++++counter%2B%3D1+++%23+equivalent+to+counter%3Dcounter%2B1%0Aprint+%22end+of+the+loop%22&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=2&curInstr=0"]
If you don’t modify the counter within the loop, the test is always True and so the loop will be repeated infinitely. To stop an infinite loop type CTRL-c. This will escape from the loop and return an error. Try it out yourself in IDLE:
</div>
<div class="syntaxhighlighter nogutter python">
<div class="line number1 index0 alt2"><code class="python plain">counter</code><code class="python keyword">=</code><code class="python value">3</code></div>
<div class="line number2 index1 alt1"><code class="python keyword">while</code> <code class="python plain">counter <</code><code class="python keyword">=</code> <code class="python value">8</code><code class="python plain">:</code></div>
<div class="line number3 index2 alt2"><code class="python spaces"> </code><code class="python functions">print</code> <code class="python string">'execute the loop body'</code></div>
<div class="line number3 index2 alt2">
In IDLE, press return twice to indicate the end of indentation.