Loops

You implement loops using the for and while statements. For example:

while expression: 
    statements 

for i in s: 
    statements
				

The while statement executes statements until the associated expression evaluates to false. The for statement iterates over all the elements in a sequence until no more elements are available. If the elements of the sequence are tuples of identical size, you can use the following variation of the for statement:

for x,y,z in s: 
    statements
				

In this case, s must be a sequence of tuples, each with three elements. On each iteration, the contents of the variables x , y , and z are assigned the contents of the corresponding tuple.

To break out of a loop, use the break statement. For example, the following function reads ...

Get Python Essential Reference, Second Edition 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.