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 # primes.py
2
3 def isprime(n):
4 # Return True if n is prime.
5 return n > 1 and smallestdivisor(n) == n
6
7 def smallestdivisor(n):
8 # Find smallest divisor (other than 1) of integer ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.