while Loops

Python’s while statement is its most general iteration construct. In simple terms, it repeatedly executes a block of indented statements, as long as a test at the top keeps evaluating to a true value. When the test becomes false, control continues after all the statements in the while, and the body never runs if the test is false to begin with.

The while statement is one of two looping statements (along with the for, which we’ll meet next). We call it a loop, because control keeps looping back to the start of the statement, until the test becomes false. The net effect is that the loop’s body is executed repeatedly while the test at the top is true. Python also provides a handful of tools that implicitly loop (iterate), such as the map, reduce, and filter functions, and the in membership test; we explore some of these later in this book.

General Format

In its most complex form, the while statement consists of a header line with a test expression, a body of one or more indented statements, and an optional else part that is executed if control exits the loop without running into a break statement (more on these last few words later). Python keeps evaluating the test at the top, and executing the statements nested in the while part, until the test returns a false value:

while <test>:             # loop test
    <statements1>         # loop body
else:                     # optional else
    <statements2>         # run if didn't exit loop with break

Examples

To illustrate, here are a handful of simple while loops in action. The ...

Get Learning 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.