Chapter 25 Definite Loops

25.1 The for statement

In Chapter 24, as you certainly noticed, the while statement was used to iterate for both a known number and an unknown number of times (in situations where the number of iterations was not known at the time the loop started iterating). In other words, the while statement was used to create both definite and indefinite loops.

Since definite loops are so frequently used in computer programming, almost every computer language, including Python, incorporates a special statement that is notably more readable and convenient than the while statement—and this is the for statement.

The general form of the for statement, is

for element in sequence:
A statement or block of statements

where element is a ...

Get Python and Algorithmic Thinking for the Complete Beginner 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.