CHAPTER 7

Repeating Actions with Loops

In this chapter, you start using Python’s loops to repeat actions as needed in your scripts. You learn to create both for loops and while loops, use loop control statements, and nest loops within each other to implement complex repetition.

Snapshot of repeating actions with loops.

Understanding Python’s Loops

Understanding How for Loops Work

Create for Loops

Understanding How while Loops Work

Create while Loops

Understanding break Statements in Loops

Using a break Statement to Exit a Loop Early

Understanding continue Statements in Loops

Using a continue Statement in a Loop

Understanding else Statements in Loops

Using an else Statement in a Loop

Understanding Loop Nesting

Nest Loops to Create Complex Repetition

Understanding Python’s Loops

When you need to repeat actions in your code, you can use Python’s loop structures. A for loop lets you iterate — repeat — actions either once for each object in a collection, such as once for each letter in a string of text, or a specific number of times, such as 10 times. A while loop enables you to repeat actions as long as a condition remains True — for example, while a value is above a specified cutoff. When you need more complex repetition, you can nest either type of loop or a mixture of the two types.

Using for Loops for Definite Iteration

A for loop enables you to repeat actions for a predetermined number of times. This type of repetition ...

Get Teach Yourself VISUALLY 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.