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