Chapter 8

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 #
 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

Get A Concise Introduction to Programming in Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.