05 Loops and Repetition
A practical guide to designing, choosing, controlling, and debugging Python loops, including counters, accumulators, nested loops, searches, and termination.
The Four Parts of a Loop
A loop repeats a block of instructions so that a program can process many values or an action until a condition changes. A well-designed loop normally has four parts:
Initialization establishes the starting value or data source.
Condition or stopping rule determines whether another repetition should occur.
Loop body contains the instructions performed during each iteration.
Progress or update changes the program state so that the loop can eventually stop.
A useful design question is: what information must the program remember from one iteration to the next? That information might be a count, a running total, a best value, a current position, or the state of a search.
Takeaway
Before writing a loop, identify its starting state, repeated work, stopping rule, and path toward progress.
Choosing Between while and for Loops
A checks its condition before each iteration and runs only while that condition is true. It is appropriate when the number of repetitions is not known in advance, such as repeatedly requesting input until it is valid or until a correct password is entered.
The condition should describe when the loop may , and the body should change something related to that condition. For example, a that starts at and increases by after each iteration eventually makes the condition false.
A is designed to process each item in an iterable, such as a list of names, or each value generated by . Use it when the program should perform an action once for every item or repeat a known number of times.
The ending value of is not included. Thus, range(2, 11, 2) generates , , , , and . When both an index and an item are needed, enumerate() provides them together and avoids manually maintaining an index.
Choose a when processing a collection, iterating through a range, or repeating a known number of times. Choose a when the stopping point depends on input or changing state.
Takeaway
Use the loop form that matches the stopping information available before the loop begins.
Counters, Accumulators, and Search
A records how many times an event occurs. Initialize it before the loop, and increase it only when the event being counted happens. For example, when examining a list of numbers, an even-number should increase only when the remainder condition identifies an even value.
Counters can track categories at the same time. Separate variables can count positive values, negative values, and zero values, with exactly one category updated for each item.
An combines values into one result. A sum usually starts at , while a product starts at , because these are the identity values for addition and multiplication. An can also build a string or collect a result in a list.
Search and aggregation often use the same general pattern:
Initialize the state, such as a count, total, or candidate answer.
Examine one item during each iteration.
Update the state when the item provides relevant information.
Use the final state as the result.
To find a largest value, begin with an initial candidate, compare each remaining value with it, and replace the candidate whenever a larger value is found.
Takeaway
Update a or at the exact point where the current item contributes to the result.
Controlling Loop Execution
immediately ends the innermost loop. It is useful when a search has found its target or when continuing would perform unnecessary work.
skips the remainder of the current iteration and starts the next one. It can simplify filtering: a loop may skip unwanted values and process only the values that remain. In a while loop, however, must not bypass the update that moves the loop toward termination.
Python also supports a loop else clause. The else block runs when the loop finishes normally, but not when the loop ends with . This makes it useful for searches: can report success, while else can report that every item was examined without success.
A is a special value that means “stop.” An input loop can repeatedly read a response and use when the response equals the sentinel. This is a deliberate use of while True, provided every possible path either makes progress or reaches a clear stopping action.
Takeaway
Use for successful early termination, for deliberate filtering, and a when input itself signals completion.
Nested Loops and Reliable Termination
A places one loop inside another. The inner loop completes all of its iterations for each iteration of the outer loop. This structure is useful for rows and columns, multiplication tables, grids, and comparisons between pairs of values.
If the outer loop runs times and the inner loop runs times for every outer iteration, the loop body executes approximately times. Nested loops can therefore require substantially more work than a single loop as the input grows.
A inside a exits only the innermost loop. The outer loop continues with its next iteration unless it has its own stopping logic.
An never reaches its stopping condition. In a while loop, check that the controlling value is initialized, that the body updates it, and that the update moves toward making the condition false. Also consider whether every possible input can eventually produce termination.
When debugging, temporarily display control variables and count iterations. If the loop does not finish, check whether the condition is always true, an update is missing, an update moves in the wrong direction, or skips a required update.
Takeaway
Analyze nested-loop cost and verify a reliable path toward termination before running a loop on large or unpredictable input.