Skip to Content
Learning Python, 6th Edition
book

Learning Python, 6th Edition

by Mark Lutz
February 2025
Intermediate to advanced
1172 pages
42h 20m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning Python, 6th Edition

Chapter 13. while and for Loops

This chapter concludes our tour of Python procedural statements by presenting the language’s two main looping constructs—statements that repeat an action over and over:

while/else
The most general looping statement, which can handle repetitive tasks of all kinds
for/else
A specialized loop designed for stepping through the items in any “iterable” object easily

We’ve met and used both of these informally already, but we’ll fill in additional usage details here. While we’re at it, we’ll also study a few less prominent statements used within loops, such as break and continue, the loop else, and cover some built-ins commonly used with loops, such as range, zip, and enumerate.

Although the while and for statements covered here are the primary syntax provided for coding repeated actions, there are additional looping operations and concepts in Python. Because of that, the iteration story is continued in the next chapter, where we’ll explore the related ideas of Python’s iteration protocol (used by the for loop) and list comprehensions (a close cousin to the for loop). Later chapters explore even more exotic iteration tools such as generators and functional tools like map, filter, and reduce. For now, though, let’s keep things simple.

while Loops

Python’s while statement is the most general iteration construct in the language. In simple terms, it repeatedly executes an associated block of statements as long as a test at the top keeps evaluating to a ...

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

Head First Python, 3rd Edition

Head First Python, 3rd Edition

Paul Barry

Publisher Resources

ISBN: 9781098171292Errata PageSupplemental Content