Chapter 13. while and for Loops

In this chapter, we’ll meet Python’s two main looping constructs—statements that repeat an action over and over. The first of these, the while statement, provides a way to code general loops; the second, the for statement, is designed for stepping through the items in a sequence object, and running a block of code for each item.

There are other kinds of looping operations in Python, but the two statements covered here are the primary syntax provided for coding repeated actions. We’ll also study a few unusual statements (such as break and continue) here because they are used within loops. Additionally, this chapter will explore the related concept of Python’s iteration protocol, and fill in some details on list comprehensions, a close cousin to the for loop.

while Loops

Python’s while statement is the most general iteration construct in the language. In simple terms, it repeatedly executes a block of (normally indented) statements as long as a test at the top keeps evaluating to a true value. It is called a “loop” because control keeps looping back to the start of the statement until the test becomes false. When the test becomes false, control passes to the statement that follows the while block. The net effect is that the loop’s body is executed repeatedly while the test at the top is true; if the test is false to begin with, the body never runs.

As I’ve just stated, the while statement is one of two looping statements available in Python, along with ...

Get Learning Python, 3rd Edition 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.