The while statement is a general-purpose tool for iteration, and is necessary for any instance of iteration where we donβt know how many repetitions will be needed. However, if we do know how many are needed, there is a more efficient approach: the for statement.
As a simple example, letβs say we have some friends, and weβd like to send them each an email inviting them to our party. We donβt quite know how to send email yet, so for the moment weβll just print a message for each friend.
Line 2 is the loop body. The loop body is always indented. The indentation determines exactly what statements are βin the loopβ. The loop body is performed one time for each name in the list.
On each iteration or pass of the loop, first a check is done to see if there are still more items to be processed. If there are none left (this is called the terminating condition of the loop), the loop has finished. Program execution continues at the next statement after the loop body.
If there are items still to be processed, the loop variable is updated to refer to the next item in the list. This means, in this case, that the loop body is executed here 7 times, and each time name will refer to a different friend.
After the word in and before the colon is an expression that must evaluate to a sequence (e.g, a string or a list or a tuple). It could be a literal, or a variable name, or a more complex expression.
Introduction of the for statement causes us to think about the types of iteration we have seen. The for statement will always iterate through a sequence of values like the list of names for the party.
Since we know that it will iterate once for each value in the collection, it is often said that a for loop creates a definite iteration because we definitely know how many times we are going to iterate. On the other hand, the while statement is dependent on a condition that needs to evaluate to False in order for the loop to terminate. Since we do not necessarily know when this will happen, it creates what we call indefinite iteration. Indefinite iteration simply means that we donβt know how many times we will repeat but eventually the condition controlling the iteration will fail and the iteration will stop (unless we have an infinite loop).
Use a for loop if you know the maximum number of times that youβll need to execute the body. For example, if youβre traversing a list of elements, or know the number of times youβll iterate, then choose the for loop.
So any problem like "iterate this weather model run for 1000 cycles", "search this list of words", or "check all integers up to 10000 to see which are prime" suggest that a for loop is best.
What you will notice here is that the while loop is more work for you β the programmer β than the equivalent for loop. When using a while loop you have to control the loop variable yourself. You give it an initial value, test for completion, and then make sure you change something in the body so that the loop terminates.