The "while" statement is more primitive than a for-loop statement. Whereas a for-loop automically assigns to a loop variable, then tests whether or not the loop body should be done, a while-loop only tests a condition.
What if Python did not have a for-loop statement? The same idea behind a for-loop could be done by recursion or by using a while-loop and assignments.
1 2 3 4 | print "Start" ,
for i in range(4):
print i ,
print "Done", i
|
The output from this example is: Start 0 1 2 3 Done 3. To get the same output from a while-loop, an attempt might be:
1 2 3 4 5 6 | i = 0
print "Start" ,
while i<4:
print i ,
i += 1
print "Done", i
|
However, the output from running this is: Start 0 1 2 3 Done 4. It seems that a for-loop does something that a straightforward while-loop does not do: it prevents the loop variable from going "too far". In later chapters, other techniques are introduced so that a while-loop can indeed more accurately simulate a for-loop (though this is just an academic exercise).