4 Loops and Iteration

A practical guide to choosing, writing, controlling, and troubleshooting Python loops for repeated computation and collection processing.

Choosing the Right Loop

Loops let a Python program execute a block of statements repeatedly. The loop body is defined by indentation, and a colon introduces the indented block.

The two primary choices are:

  • A repeats according to a condition.

  • A visits items supplied by an .

Choose the loop based on what determines completion. If the program should while a changing condition is true, use a . If the program should process each item in a collection or a known integer sequence, use a .

Takeaway: Let the source of repetition determine the loop: a condition suggests while, while items or a sequence suggest for.

Condition-Controlled Repetition

A checks its condition before each iteration. If the condition is true, Python runs the indented body and then checks the condition again. When the condition becomes false, execution continues after the loop.

A useful changes the state that controls its condition. For example, a counter can begin at an initial value, be displayed or processed, and then be increased on each pass until it reaches its limit. If no relevant state changes, the condition may remain true forever.

A is useful when the number of repetitions is unknown. The program can repeatedly request input, compare each response with a designated stopping value, and use that value to leave the loop. A is also well suited to input validation: keep requesting a value until it satisfies the required rule.

Takeaway: Before writing a , identify what changes on every pass and explain why that change will eventually make the condition false.

Iterating Through Items

A assigns one item from an to its loop variable on each iteration. It can process a list, string, tuple, dictionary, set, or object directly.

Direct iteration is usually clearer than manually managing an index. For example, a loop can visit each color in a collection or each character in a word without calculating positions. When both a position and an item are required, supplies them together and can begin counting at a chosen index.

The loop variable is reassigned automatically for every iteration. Changing that variable inside the body does not change the next item supplied by the .

Takeaway: Ask the for its next item directly; use only when the position is part of the task.

Integer Sequences with

The object supplies integers for a without first constructing a list containing every value. Its common forms are range(stop), range(start, stop), and range(start, stop, step).

The stop value is excluded. Thus, a sequence intended to include values from one through five uses a stopping value of six. A positive step moves upward, while a negative step moves downward. A zero step is invalid, and a range can be empty when its direction cannot reach the stopping boundary.

Excluding the stop value is a frequent source of off-by-one errors. Check the first value, the final value that should be included, and the direction before choosing the arguments.

Takeaway: Treat the stop argument as a boundary rather than an included endpoint, and verify the direction of the step.

Controlling Loop Execution

Loop control changes what happens during iteration:

  • ends the innermost enclosing loop immediately.

  • skips the rest of the current iteration and starts the next one.

  • A clause runs only when the loop completes without .

The pattern is particularly useful for searching. Test each item, use when the target is found, and place the not-found action in the clause. If the target is found, prevents the else block from running; if the is exhausted without a match, the else block runs.

In nested loops, exits only the inner loop containing it. The outer loop continues unless it has its own control path.

Takeaway: Use to stop, to skip, and to handle normal completion after an unsuccessful search.

Common Patterns and Safe Practices

Loops support several reusable problem-solving patterns.

  • Accumulation: initialize a result before the loop and update it for each item. For a simple total, the built-in sum() function may express the intention more directly.

  • Counting: initialize a counter and increase it only when an item satisfies a condition.

  • Finding: store a matching item and use when the first match is enough. For simple membership checks, the in operator may be clearer.

  • Filtering: build a new collection containing only items that pass a condition.

  • Pairing: use to process corresponding items from multiple iterables.

  • Nesting: place one loop inside another for grids, tables, or pairwise comparisons.

Avoid changing a collection while directly iterating over that same collection. Removing or rearranging items during traversal can cause items to be skipped or produce confusing results. Construct a new collection or iterate over a separate copy instead.

Keep each loop focused on one task. Descriptive variable names, small helper functions, and simpler stages can make a complicated loop easier to verify.

Takeaway: Initialize state clearly, update it deliberately, and choose the simplest built-in or loop pattern that expresses the task.

Loop Review Checklist

Use this checklist to review a loop:

  1. Identify whether completion depends on an , a known integer sequence, or a changing condition.

  2. If using a , confirm that the controlling state changes and that termination is reachable.

  3. If using , check whether the stop value is excluded and whether the step has the correct direction.

  4. Confirm that indentation places every intended statement inside or outside the loop correctly.

  5. Check whether and affect the innermost loop as intended.

  6. For a search, decide whether a clause clearly expresses the not-found case.

  7. Avoid modifying the collection currently being traversed.

  8. Consider whether direct iteration, , , sum(), or a membership test makes the code clearer.

Common failures include infinite while loops, off-by-one boundaries, empty ranges caused by an incompatible direction, and incorrect assumptions about changing the loop variable inside a .

Final takeaway: A reliable loop has a clear source of repetition, a visible stopping rule, and a body whose state changes and control flow are easy to follow.