Repetition: While Loops
While loops allow programs to repeat without necessarily knowing ahead of time how many times the loop will run. Like selection, this allows programs to adapt and run more or less code, depending on the circumstances.
Consider the task of printing a table of prime numbers. An integer n is prime if it is greater than 1 and its only positive divisors are 1 and itself. This definition leads to the following program:
Listing 8.1: Prime Numbers
1 # primes.py
3 def isprime(n):
4 # Return True if n is prime.
5 return n > 1 and smallestdivisor(n) == n
7 def smallestdivisor(n):
8 # Find smallest divisor (other than 1) of integer n > 1.
9 k = 2
10 while k < n and not divides(k, n):
11 k += 1
12 return k