in loop tests. You can move the assignment into the loop body with a break:
while True:
x = next()
if not x: break
...process x...
or move the assignment into the loop with tests:
x = True
while x:
x = next()
if x:
...process x...
or move the first assignment outside the loop:
x = next()
while x:
...process x...
x = next()
Of these three coding patterns, the first may be considered by some to be the least structured, but it also seems to be the simplest and is the most commonly used. A simple Python for loop may replace some C loops as well.
* * *
for Loops
The for loop is a generic sequence iterator in Python: it can step through the items in any ordered sequence object. The for statement works on strings, lists, tuples, other built-in iterables, and new objects that we’ll see how to create later with classes. We met it in brief when studying sequence object types; let’s expand on its usage more formally here.
General Format
The Python for loop begins with a header line that specifies an assignment target (or targets), along with the object you want to step through. The header is followed by a block of (normally indented) statements that you want to repeat: