Loops · 17 min

Control loops with while, break, and continue

Repeat until a condition changes, skip records, and stop early.

Jump to the automation lab

A while loop rechecks its condition before each pass. Make sure each pass moves toward the stopping condition. A for loop is usually clearer when the inputs already form a sequence.

break exits the innermost loop. continue skips the rest of the current pass. For a search, you can also return directly when you find a match and return None when no match exists.

Nested loops repeat once per combination. With an outer loop over rows and an inner loop over columns, complete each row before starting the next.

Follow the example

continue moves directly to the next line.

Worked examples

Count down with while

The condition is checked before each pass. Updating remaining guarantees it eventually reaches zero.

countdown.py
remaining = 3
while remaining > 0:
    print(remaining)
    remaining -= 1
print("Ready")

Draw a grid with nested loops

The outer loop produces two rows. Each row receives three column markers from the inner loop.

grid.py
for row in range(2):
    cells = []
    for column in range(3):
        cells.append(f"{row},{column}")
    print(" | ".join(cells))

Run the example and practice

Extend total_before_end so it strips each line and skips blank lines. Replace the sample with [" ", " 7 ", "# note", "8", " END ", "90"].

Target output

15
Show a hint

Strip the current line before testing for the sentinel, a blank, or a comment.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
def total_before_end(lines):
    total = 0
    for line in lines:
        line = line.strip()
        if line == "END":
            break
        if not line or line.startswith("#"):
            continue
        total += int(line)
    return total

print(total_before_end([" ", " 7 ", "# note", "8", " END ", "90"]))

Automation lab

Read a queue until the shift ends

Skip blank entries and stop at the handoff marker. Later jobs belong to the next shift.

Output

Ready

Run the example to see the output here.

Move HANDOFF to the first position. Predict what the loop will print.

Further reading in Automate the Boring Stuff with Python by Al Sweigart