3.8 while loops

while loops are like for loops in that they are used to repeat the nested block following them a number of times. However, the number of times the block is repeated can be variable: the nested block will be repeated whilst a condition is satisfied. At the top of the while loop a condition is tested and if true, the loop is executed.

    while [condition]:
       [statements executed if the condition is true]

    [rest of program]

Here is a short example:

    i = 1
    while i < 10:
        print "i equals:", i
        i = i + 1
    print "i is no longer less than ten"

Recall the role of indentation. The last line is not executed each time the while condition is satisfied, but rather once it is not, and Python has jumped to [rest of program].

The [conditon] used at the top of the while loop is of the same form as those used in if statements: see Section 3.7.2, ``Comparison tests and Booleans''

Here is a longer example that uses the % (remainder) operator to return the smallest factor of a number entered by a user:

    print """ 
    This program returns the smallest non-unity
    factor (except one!) of a number entered by the user 
    n = input("number: ") 
    i = 2                      # Start at two -- one is a factor of 
                               # everything

    while (n % i) != 0:        # i.e. as long as the remainder of n / i
       i = i + 1               # is non-zero, keep incrementing i by 1.

    # once control has passed to the rest of the program we know i is a 
    # factor.

    print "The smallest factor of n is:", i

This program does something new with strings. If you want to print lines of text and control when the next line is started, enclose the string in three double quotes and type away.

This is the most complex program you have seen so far. Make sure you try running it yourself. Convince yourself that it returns sensible answers for small n and try some really big numbers.

Modify the above example of while so that it tells the user whether or not the number they have entered is a prime. Hint: think about what can be said about the smallest factor if the number is prime. Some really big primes you could try with your program are 1,299,709 and 15,485,863. Note that this is far from the most efficient way of computing prime numbers!