Skip to Content
Learning Python, 2nd Edition
book

Learning Python, 2nd Edition

by Mark Lutz, David Ascher
December 2003
Beginner
620 pages
17h 3m
English
O'Reilly Media, Inc.
Content preview from Learning Python, 2nd Edition

Chapter 10. while and for Loops

In this chapter, we meet Python’s two main looping constructs—statements that repeat an action over and over. The first of these, the while loop, 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.

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 block; 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). It is called 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. Besides statements, Python also provides a handful of tools that implicitly loop (iterate): the map, reduce, and filter functions; the in membership test; list comprehensions; and more. We’ll explore most of these in Chapter 14.

General Format ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python, 5th Edition

Learning Python, 5th Edition

Mark Lutz

Publisher Resources

ISBN: 0596002815Supplemental ContentErrata Page