0% complete

Control flow and Python collections · Lesson 2 of 3

Loops, iteration, and stopping conditions

Use for and while loops safely, including break, continue, and enumerate.

Lesson

1. Concept and mental model

A for loop processes items from an iterable such as a list, string, file, or range. This is the normal way to visit a known collection; avoid manually maintaining an index when you do not need one. Use enumerate(items, start=1) when both the item and its display number are useful. A while loop repeats while a condition remains true and is appropriate when the number of attempts is not known in advance.

2. How it works

Every while loop needs a state change or exit path that can eventually make its condition false. Otherwise the program can run forever. break exits the nearest loop; continue skips the rest of the current iteration. These controls are useful, but deeply nested loops with many early exits are difficult to reason about. Extract a function when a loop becomes too complex.

3. Use it safely and effectively

Loop else blocks run only when a loop ends normally, not when break stops it. Because this behavior surprises beginners, use it only when it makes a search or validation clearer. For large or infinite streams, process one item at a time rather than collecting everything into a list. Handle empty iterables and missing matches explicitly; loops should express the full behavior, including what happens when there is nothing to process.

4. Syntax reference

tasks = ['backup', 'report', 'cleanup']
for number, task in enumerate(tasks, start=1):
    print(f'{number}. {task}')

5. Types of loops and loop controls in Python

for loop: visit each item

A for loop takes the next value from any iterable, such as a list, string, dictionary, file, or range. It is the usual choice when processing every item or repeating a known number of times.

for item in iterable:
    # use item
    print(item)

for number in range(1, 4):
    print(number)

while loop: repeat while a condition is true

A while loop checks its condition before each iteration and stops when that condition becomes false. Update the state used by the condition inside the loop so it can eventually finish.

count = 1
while count <= 3:
    print(count)
    count += 1

Nested loops: a loop inside another loop

A nested loop runs its inner loop for each iteration of the outer loop. Use it for combinations, grids, and two-dimensional data; remember that work grows with the product of both iteration counts.

for row in range(1, 3):
    for column in range(1, 3):
        print(row, column)

Loop else: run when no break occurred

Python also allows an else clause on for and while loops. The else block runs after normal exhaustion or a false condition, but it is skipped when the loop exits with break. It is not an if/else for each iteration.

for value in [2, 4, 6]:
    if value % 2:
        print('found odd')
        break
else:
    print('all even')

break, continue, and pass

break exits the nearest loop immediately; continue skips to its next iteration; pass does nothing and is a placeholder where Python syntax requires a statement. These are loop controls, not additional loop types.

for number in range(1, 6):
    if number == 2:
        continue
    if number == 5:
        break
    print(number)

There is no built-in do-while loop

Python has for and while statements, but no separate do-while statement. To ensure a task runs once before checking whether to repeat, perform the first operation before entering a while loop or use an explicit loop-and-break pattern.

while True:
    answer = input('Continue? ')
    if answer == 'no':
        break

6. Guided walkthrough

Use for when each item or a known range is available, and use while only when repetition depends on a condition changing. Trace the loop variable through the first, middle, and final iterations, then check that the loop has a clear stopping condition.

7. Common mistakes to avoid

  • Forgetting to update the condition in a while loop, creating an infinite loop.
  • Expecting range(1, 5) to include 5; the stop value is excluded.

Visual guide

Process a collection

  1. Step 01 Get item

    The iterator yields its next value.

  2. Step 02 Process

    Run the loop body for that value.

  3. Step 03 Continue

    Finish when the iterator is exhausted.

Code examples

Worked example
PYTHON
tasks = ['backup', 'report', 'cleanup']
for number, task in enumerate(tasks, start=1):
    print(f'{number}. {task}')
Expected output
1. backup
2. report
3. cleanup
Accumulate values with a for loop
PYTHON
total = 0
for number in [4, 7, 2]:
    total += number
print(total)
Expected output
13
Stop when a sentinel is reached
PYTHON
items = ['ready', 'ready', 'stop', 'ignored']
for item in items:
    if item == 'stop':
        break
    print(item)
Expected output
ready
ready

Key points

  • Use for and while loops safely, including break, continue, and enumerate.
  • Prefer explicit, testable behavior over hidden side effects.
  • Validate assumptions at system boundaries and handle failure deliberately.

Check your understanding

Practice

Which built-in provides both a sequence number and each item?

Your learning progress

Finish this lesson