Loops – While VS. For

In Python, a for-loop iterates over an iterable expression and the number of times the statements in the loop are executed is known before execution.   A while-loop is controlled by a conditional expression. Every for-loop can be written as a while loop; the condition is based on number of times the for-loop executes its statements as shown in Example 9. However, not all languages allow writing a while loop as a for-loop.

In many situations, a while loop as well as a for-loop can be used. However, sometimes the algorithm underlying each loop type can be different. Example 11 shows a slightly different approach using a for-loop for example 6 which used a while loop. Example 12 shows two very different algorithms for determining the greatest common divisor of two integers, one using a while-loop and one using a for-loop.

Example 9: Converting a for-loop into a while loop

Example 10: Are all these loops doing the same thing? 

Example 11: Sum up the digits in an integer (with video) 

Example 12: Find the greatest common divisor (GCD) of two integers.