Loop and Iteration
A loop repeats a block of code. One pass through the block is an iteration, and an object that can supply its values one at a time is iterable. Strings, lists, tuples, dictionaries, files, and range() objects are all iterable, which is why the same loop shape works across them.
A for loop takes each value of an iterable in turn and binds it to the loop variable: for row in rows:. Use it to consume an iterable, even a file or generator whose length is not known in advance. range(stop) produces whole numbers from 0, range(start, stop) sets the first value, and a third argument sets the step; the stop value is always excluded. For step 1, use endpoint + 1 to include an integer endpoint. Other steps must actually land on that endpoint; a zero step raises ValueError. A range object generates its numbers as needed rather than storing them all.
A while loop repeats as long as its condition is true, which suits work whose number of repetitions is not known in advance, such as reading until input runs out. A counter-controlled loop needs initialization and an update toward its stopping condition. Other loops may end when external state changes or break runs; not every while loop needs a counter update. A loop that must terminate deserves a bound, such as a maximum number of attempts, alongside its main condition.
break leaves the innermost loop immediately, and continue skips the rest of the current iteration and starts the next one. Both apply only to the loop that contains them, so a break inside nested loops exits one level. Two habits prevent common bugs: do not add or remove items from a collection while iterating over it, and do not assume the loop body ran at all, because an empty iterable or an initially false condition skips it entirely, leaving an initialized result unchanged. A name assigned only inside a skipped body remains undefined if it did not exist before. In a while loop, continue rechecks the condition; skipping the needed update can prevent termination.
References: Python tutorial: for statements, range. See it in use in Python Strings, Conditions, and Loops.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
